有一个有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连接的自写组合函数。结果不是我所期望的那样。无法理解结果的行为
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
发布于 2018-06-20 11:21:18
一行:
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]如果您的dataframe中有更多列,它们也将被聚合到列表中。如果是这样,并且只希望properties_id成为一个列表,则只需在.agg()中指定该列即可。
df.groupby('goods_id').agg({'properties_id': lambda col: col.tolist()}).reset_index()https://stackoverflow.com/questions/50946906
复制相似问题