熊猫合并列以使用逗号分隔的值创建新列

KRD*_*vis 8 python merge comma multiple-columns pandas

我的数据框有四列颜色。我想将它们合并到一个称为“颜色”的列中,并使用逗号分隔值。

例如,我正在尝试合并成这样的Colors列:

ID  Black Red  Blue  Green  Colors   
120 NaN   red  NaN   green  red, green  
121 black Nan  blue  NaN    black, blue
Run Code Online (Sandbox Code Playgroud)

我的代码是:

df['Colors'] = df[['Black, 'Red', 'Blue', 'Green']].apply(lambda x: ', '.join(x), axis=1)
Run Code Online (Sandbox Code Playgroud)

但是ID 120的输出是:,红色,,绿色

ID 121的输出为:黑色,蓝色,

发现我的问题!在我的代码前面,我用“”代替了NaN来代替“ None”。进行更改后,再加上反馈以插入[x.notnull()],就可以了!

df['Black'].replace('None', np.nan, inplace=True)
df['Colors'] = df[['Black, 'Red', 'Blue', 'Green']].apply(lambda x: ', '.join(x[x.notnull()]), axis=1)
Run Code Online (Sandbox Code Playgroud)

Vai*_*ali 5

您只需要处理NaN

df['Colors'] = df[['Black', 'Red', 'Blue', 'Green']].apply(lambda x: ', '.join(x[x.notnull()]), axis = 1)

    ID      Black   Red Blue    Green   Colors
0   120     NaN     red NaN     green   red, green
1   121     black   NaN blue    NaN     black, blue
Run Code Online (Sandbox Code Playgroud)