【问题标题】:Aggregating df columns but not duplicates聚合 df 列但不聚合
【发布时间】:2023-01-10 12:25:24
【问题描述】:

有没有一种巧妙的方法可以在不重复信息的情况下将列聚合到一个新列中?

例如,如果我有一个 df:

     Description  Information
  0       text1     text1
  1       text2     text3
  2       text4     text5

我想创建一个名为“Combined”的新列,它聚合了“Description”和“Information”以获得:

     Description  Information  Combined
  0       text1     text1        text1
  1       text2     text3      text2 text3
  2       text4     text5      text4 text5

到目前为止,我一直在使用 np.where 和 [mask] 在与 df['Combined'] = df[['Description', 'Information']].agg(' '.join, axis=1) 聚合之前检查重复项

虽然这可行,但在更大范围内并不实用,如果有人知道更简单的方法,将不胜感激!

【问题讨论】:

    标签: python pandas string aggregate


    【解决方案1】:

    你可以先运行unique

    df['Combined'] = df[['Description', 'Information']].agg(lambda x: ' '.join(x.unique()), axis=1)
    

    【讨论】:

      【解决方案2】:

      你可以在agg中使用lambda

      df['Combined'] = df[['Description', 'Information']].agg(lambda x: ' '.join(set(x)), axis=1)
      print(df)
      

      输出:

        Description Information     Combined
      0       text1       text1        text1
      1       text2       text3  text2 text3
      2       text4       text5  text5 text4
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-09
        • 2017-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多