在 pandas 中的 groupby 之后将 int64 合并到整数列表中

combine int64 into list of integers after groupby in pandas

有一个包含 2 列的 df

goods_id         int64
properties_id    int64
dtype: object

df
      goods_id  properties_id
    0   3588    1
    1   3588    2
    2   3588    3
    3   3588    4
    4   3588    5
    5   3588    6
    6   3589    1
    7   3589    2
    8   3589    3

需要将 properties_ids 行合并到每个组的整数列表中。换句话说,每个 group_id 3588 [1,2,3,4,5,6]3589 [1,2,3] 等的期望输出。为了得到它,我使用基于 ','.join 连接的自写组合函数。结果不是我期望得到的。无法理解 result

的行为
def combine(x):
    return ','.join(x)

df.groupby('goods_id').apply(combine)

goods_id
3588    goods_id,properties_id # desired output [1,2,3,4,5,6]
3589    goods_id,properties_id # desired output [1,2,3]

使用 df.groupby('goods_id')['properties_id'].apply(combine) 给我 TypeError: sequence item 0: expected str instance, int found

一行:

df.groupby('goods_id').agg(lambda col: col.tolist()).reset_index()

给出以下数据框:

   goods_id       properties_id
0      3588  [1, 2, 3, 4, 5, 6]
1      3589           [1, 2, 3]

如果您的数据框中有更多列,它们也会聚合到列表中。如果是这种情况,而你只想让properties_id成为一个列表,你只需要在.agg()中指定这一列:

df.groupby('goods_id').agg({'properties_id': lambda col: col.tolist()}).reset_index()