1

I want to join multiple columns of the same dataframe into a single column. The columns dosent have any labels.

input:

 0  1  2  3  4
 a  b  c  d  e

Result:

0
a,b,c,d,e

please help me with this.

I already tried data1['all'] = data[data.columns[1:]].apply(lambda x: ','.join(x.dropna().astype(str)),axis=1)

but I am not able to get the result as required.

1
  • Can yo ube more specific why not working? Why first column is removed? Commented Apr 1, 2020 at 11:13

2 Answers 2

4

Your solution working for me with small modification removed filering out first column and assign to same DataFrame:

data['all'] = data.apply(lambda x: ','.join(x.dropna().astype(str)),axis=1)

If no missing values and no numeric values:

data['all'] = data.apply(','.join,axis=1)

print (data)
   0  1  2  3  4        all
0  a  b  c  d  e  a,b,c,d,e

If need new one column DataFrame:

df = = data.apply(lambda x: ','.join(x.dropna().astype(str)),axis=1).to_frame('new')
#df = data.apply(','.join,axis=1).to_frame('new')
print (df)
         new
0  a,b,c,d,e
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot for your help. Although, I am thinking my data is somewhat poor that is why i am having the issue.
I am still not sure. I started working on dummy data and will late import the real data and will see if it is working or not. Thanks a lot for your help and concern. will update asap.
@RajRajeshwariPrasad - Super! Let me know how it will work
0

You could avoid apply altogether and use Pandas' built in string methods ; in this case , string concatenate

#merge the other columns to '0' and specify a delimiter
df['0'].str.cat(df.loc[:,'1':],sep=',')

 0    a,b,c,d,e
Name: 0, dtype: object  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.