我有一个事务格式的pandas数据帧:
id purchased_item
1 apple
1 banana
1 carrot
2 banana
3 apple
4 apple
4 carrot
4 diet coke
5 banana
5 carrot
6 banana
6 carrot
我想将其转换为以下内容:
[['apple', 'banana', 'carrot'],
['banana'],
['apple'],
['apple', 'carrot', 'diet coke'],
['banana', 'carrot'],
['banana', 'carrot']]
我试过这个:
df.groupby(['id'])['purchased_item'].apply(list)
输出看起来像:
customer_id
1 [apple, banana, carrot]
2 [banana]
3 [apple]
4 [apple, carrot, diet coke]
5 [banana, carrot]
6 [banana, carrot]
下一步该怎么办?还是有不同的方法?非常感谢你的帮助。
您在问答评论中提到的解决方案:
df.groupby(['id'])['purchased_item'].apply(list).values.tolist()
In [434]: df.groupby(['id'])['purchased_item'].apply(list).values.tolist()
Out[434]:
[['apple', 'banana', 'carrot'],
['banana'],
['apple'],
['apple', 'carrot', 'diet_coke'],
['banana', 'carrot'],
['banana', 'carrot']]
编辑
与@Colonel Beauvel解决方案相比的一些测试性能:
In [472]: %timeit [gr['purchased_item'].tolist() for n, gr in df.groupby('id')]
100 loops, best of 3: 2.1 ms per loop
In [473]: %timeit df.groupby(['id'])['purchased_item'].apply(list).values.tolist()
1000 loops, best of 3: 1.36 ms per loop
我宁愿使用理解列表使用不同的解决方案:
[gr['purchased_item'].tolist() for n, gr in df.groupby('id')]
Out[9]:
[['apple', 'banana', 'carrot'],
['banana'],
['apple'],
['apple', 'carrot', 'dietcoke'],
['banana', 'carrot'],
['banana', 'carrot']]