【问题标题】:Group by the all the columns except the first one, but aggregate as list the first column按除第一列以外的所有列分组,但聚合为列出第一列
【发布时间】:2023-01-25 02:34:43
【问题描述】:

比方说,我有这个数据框:

df = pd.DataFrame({'col_1': ['yes','no'], 'test_1':['a','b'], 'test_2':['a','b']})

我想要的是对除第一列以外的所有列进行分组,并汇总分组依据相同的结果。

这就是我正在尝试的:

col_names = df.columns.to_list()

df_out = df.groupby([col_names[1:]])[col_names[0]].agg(list)

这是我的最终数据框目标:

df = pd.DataFrame({'col_1': [['yes','no']], 'test_1':['a'], 'test_2':['b']})

而且,如果我有更多行,我希望它以相同的原则运行,加入基于列 [1:] 的相同组列表(从第二个到最后。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用熊猫agg()方法

    df = df.groupby(df.columns.difference(["col_1"]).tolist()).agg(
        lambda x: x.tolist()).reset_index()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 2020-11-27
      • 1970-01-01
      • 2021-09-21
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多