简体   繁体   English

pandas df 到 python 嵌套字典

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM