pandas 合并列以创建具有逗号分隔值的新列

pandas merge columns to create new column with comma separated values

我的数据框有四列颜色。我想将它们合并到一个名为 "Colors" 的列中,并使用逗号分隔这些值。

例如,我正在尝试像这样合并到颜色列中:

ID  Black Red  Blue  Green  Colors   
120 NaN   red  NaN   green  red, green  
121 black Nan  blue  NaN    black, blue

我的代码是:

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

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

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

找到我的问题! 在我的代码的前面,我将 "None" 替换为“”而不是 NaN。进行更改后,加上反馈以插入 [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)

你只需要处理 NaNs

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

使用dot

s=df.iloc[:,1:]
s.notnull()
   Black   Red   Blue  Green
0  False  True  False   True
1   True  True   True  False
s.notnull().dot(s.columns+',').str[:-1]
0         Red,Green
1    Black,Red,Blue
dtype: object

df['color']=s.notnull().dot(s.columns+',').str[:-1]