Concatenate cells into a string with separator pandas python

前端 未结 5 1899
暖寄归人
暖寄归人 2021-02-14 16:53

Given the following:

df = pd.DataFrame({\'col1\' : [\"a\",\"b\"],
            \'col2\'  : [\"ab\",np.nan], \'col3\' : [\"w\",\"e\"]})

I would l

5条回答
  •  既然无缘
    2021-02-14 17:36

    You can use dropna()

    df['col4'] = df.apply(lambda row: '*'.join(row.dropna()), axis=1)
    

    UPDATE:

    Since, you need to convert numbers and special chars too, you can use astype(unicode)

    In [37]: df = pd.DataFrame({'col1': ["a", "b"], 'col2': ["ab", np.nan], "col3": [3, u'\xf3']})
    
    In [38]: df.apply(lambda row: '*'.join(row.dropna().astype(unicode)), axis=1)
    Out[38]: 
    0    a*ab*3
    1       b*ó
    dtype: object
    
    In [39]: df['col4'] = df.apply(lambda row: '*'.join(row.dropna().astype(unicode)), axis=1)
    
    In [40]: df
    Out[40]: 
      col1 col2 col3    col4
    0    a   ab    3  a*ab*3
    1    b  NaN    ó     b*ó
    

提交回复
热议问题