大 pandas :将数据帧转换为列表的列表 [英] Pandas: Convert dataframe to dict of lists
本文介绍了大 pandas :将数据帧转换为列表的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数据框:
I have a dataframe like this:
col1, col2
A 0
A 1
B 2
C 3
我想得到这个:
{ A: [0,1], B: [2], C: [3] }
我试过:
df.set_index('col1')['col2'].to_dict()
但这不是很正确。我遇到的第一个问题是A,我最终会得到A:1(0被覆盖)。怎么修?
but that is not quite correct. The first issue I have is 'A' is repeated, I end up getting A:1 only (0 gets overwritten). How to fix?
推荐答案
您可以在groupby上使用字典理解。
You can use a dictionary comprehension on a groupby.
>>> {idx: group['col2'].tolist()
for idx, group in df.groupby('col1')}
{'A': [0, 1], 'B': [2], 'C': [3]}
这篇关于大 pandas :将数据帧转换为列表的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文