简体   繁体   English

将 Dataframe 转换为 Python 中的嵌套字典/树

[英]Converting Dataframe to nested dictionary/tree in Python

Right now I have a CSV file that looks like this:现在我有一个 CSV 文件,如下所示:

我的 csv 文件中的当前数据

I need to convert this data to a nested dictionary, where there are different levels, depending on the levels (or columns) in my table.我需要将此数据转换为嵌套字典,其中有不同的级别,具体取决于表中的级别(或列)。 The result should look like this:结果应如下所示:

dictionary = {A:{C:1,D:{G:2,H:3},E:4},B:{C:{I:2,J:3},D:10}} 

In other words, if there is a 'child' to the column, there needs to be another level of depth in the tree.换句话说,如果该列有一个“子级”,则树中需要有另一个深度级别。

Is there any function in Python that can do this? Python中有没有function可以做到这一点? Or do I need to write my own function?或者我需要自己写 function 吗?

how to use groupby如何使用分组

my_dict = df.groupby('A')[['B','C','D']]
       .apply(lambda x: x.set_index('B').to_dict(orient='index'))
       .to_dict()

print (my_dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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