[英]pandas df to python nested dict
Assume I have df
below:假设我在下面有
df
:
df = pd.DataFrame({
'A': ['a', 'b'],
'B': [1, 2],
'C': [3, 4]
})
How can I turn this into a nested dict
of the format:我怎样才能把它变成格式的嵌套
dict
:
{'a': {'B': 1, 'C': 2}, 'b': {'B': 3, 'C': 4}}
I've tried df.to_dict()
which doesn't return the format I'm after.我试过
df.to_dict()
不返回我所追求的格式。
Thanks!谢谢!
Try set_index
尝试
set_index
df.set_index('A').to_dict('index')
Out[8]: {'a': {'B': 1, 'C': 3}, 'b': {'B': 2, 'C': 4}}
You can set A
as index and use to_dict
:您可以将
A
设置为索引并使用to_dict
:
df.set_index('A').to_dict('i')
# {'a': {'B': 1, 'C': 3}, 'b': {'B': 2, 'C': 4}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.