【问题标题】:pandas merge columns to create new column with comma separated values熊猫合并列以使用逗号分隔值创建新列
【发布时间】:2019-05-28 16:12:56
【问题描述】:

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

例如,我正在尝试像这样组合成一个颜色列:

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)

【问题讨论】:

    标签: python pandas merge multiple-columns comma


    【解决方案1】:

    使用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]
    

    【讨论】:

      【解决方案2】:

      你只需要处理 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
      

      【讨论】:

        猜你喜欢
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-09
        • 2021-10-13
        • 1970-01-01
        • 2011-06-19
        • 1970-01-01
        • 2022-01-18
        相关资源
        最近更新 更多