pandas 数据框到字典 [英] Pandas dataframe to dict of dict
本文介绍了 pandas 数据框到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下熊猫数据框:
ColA ColB ColC
0 a1 t 1
1 a2 t 2
2 a3 d 3
3 a4 d 4
我想得到字典的字典.
但是我只能创建以下内容:
But I managed to create the following only:
d = {t : [1, 2], d : [3, 4]}
作者:
d = {k: list(v) for k,v in duplicated.groupby("ColB")["ColC"]}
我如何获得字典的字典:
How could I obtain the dict of dict:
dd = {t : {a1:1, a2:2}, d : {a3:3, a4:4}}
推荐答案
您可以预先通过groupby
+ apply
步骤执行此操作.
You can do this with a groupby
+ apply
step beforehand.
dd = df.set_index('ColA').groupby('ColB').apply(
lambda x: x.ColC.to_dict()
).to_dict()
或者,通过dict理解:
Or, with a dict comprehension:
dd = {k : g.ColC.to_dict() for k, g in df.set_index('ColA').groupby('ColB')}
print(dd)
{'d': {'a3': 3, 'a4': 4}, 't': {'a1': 1, 'a2': 2}}
这篇关于 pandas 数据框到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文