Merge multiple column values into one column in python pandas

后端 未结 3 1723
我寻月下人不归
我寻月下人不归 2020-11-28 03:07

I have a pandas data frame like this:

   Column1  Column2  Column3  Column4  Column5
 0    a        1        2        3        4
 1    a        3        4            


        
3条回答
  •  野性不改
    2020-11-28 03:21

    You can call apply pass axis=1 to apply row-wise, then convert the dtype to str and join:

    In [153]:
    df['ColumnA'] = df[df.columns[1:]].apply(
        lambda x: ','.join(x.dropna().astype(str)),
        axis=1
    )
    df
    
    Out[153]:
      Column1  Column2  Column3  Column4  Column5  ColumnA
    0       a        1        2        3        4  1,2,3,4
    1       a        3        4        5      NaN    3,4,5
    2       b        6        7        8      NaN    6,7,8
    3       c        7        7      NaN      NaN      7,7
    

    Here I call dropna to get rid of the NaN, however we need to cast again to int so we don't end up with floats as str.

提交回复
热议问题