4

I need to concentrate values to list in first cell of each column in first row

My data frame:

df = pd.DataFrame({
    'A':['one','one','two'],
    'B':[2,np.nan,2],
    'C':['main','main','main']
})
print(df)
     A    B     C
0  one  2.0  main
1  one  NaN  main
2  two  2.0  main

expected output:

    A              B           C
0  one,one,two  2.0,2.0  main,main,main

for one column, its not problem because I can use tolist() but in ths case i've tried to use :

df=df.apply(lambda x: ','.join(x.dropna().values.tolist()), axis=1)

from this topic:

Concatenate cells into a string with separator pandas python but in there , it's not a list but a string, anyway I am receiving : TypeError: ('sequence item 1: expected str instance, float found', 'occurred at index 0')

sygneto
  • 1,761
  • 1
  • 13
  • 26

1 Answers1

3

You can convert the column to string and join:

df.agg(lambda x: ','.join(x.dropna().astype(str)))

Output:

A       one,one,two
B           2.0,2.0
C    main,main,main
dtype: object

To get a dataframe, you can chain that with .to_frame().T:

df.agg(lambda x: ','.join(x.dropna().astype(str))).to_frame().T

gives you

              A        B               C
0  one,one,two  2.0,2.0  main,main,main
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74