【问题标题】:Group by several columns and add values from last column to list [duplicate]按几列分组并将最后一列的值添加到列表[重复]
【发布时间】:2023-01-26 18:11:17
【问题描述】:

我有这张桌子:

id type text
1 inv_num 123
1 company ASD
1 item fruit
1 item vegetable
2 inv_num 123
2 company FOO
2 item computer
2 item mouse
2 item headphones

我想以列表格式将相同类型分组在一行中:

id type text
1 inv_num 123
1 company ASD
1 item ['fruit', 'vegetable']
2 inv_num 123
2 company FOO
2 item ['computer', 'mouse', 'headphones']

是否可以使用“groupby”来做到这一点?

【问题讨论】:

  • 如果您只需要包含多个项目的组的列表:使用lambda x: list(x) if len(x)>1 else x作为聚合函数

标签: python pandas


【解决方案1】:

如果仅当值的长度大于 1 时才需要列表,请在 GroupBy.agg 中使用自定义 lambda 函数:

f = lambda x: x.tolist() if len(x) > 1 else x
df = df.groupby(['id','type'])['text'].agg(f).reset_index()
print (df)
   id     type                           text
0   1  company                            ASD
1   1  inv_num                            123
2   1     item             [fruit, vegetable]
3   2  company                            FOO
4   2  inv_num                            123
5   2     item  [computer, mouse, headphones]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2020-10-27
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多