在 pandas 数据框中创建父子对字典 [英] Creating dictionary of parent child pairs in pandas dataframe
本文介绍了在 pandas 数据框中创建父子对字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含两列的数据框:
I have a dataframe with two columns as:
CHILD PARENT
1 2
2 3
3 4
10 11
11 12
我需要创建一个字典,其中将顶部父项作为键,并将其所有后代作为一组值,例如:
I need to create a dictionary where I keep the top parent as key and all its descendents as set of values, like:
4: [1,2,3]
12: [10,11]
通过以下链接中的代码,我已经能够从该数据框中提取 12 和 4 作为顶级父项:
I have been able to extract 12 and 4 as top parents from this dataframe, by code from following link:
现在,我不知道如何在 python 中做到这一点.在java中,我可以通过遵循dfs来做到这一点.有什么建议吗?
Now, I have no idea how to do this in python. In java I can do this by following a dfs. Any suggestions?
推荐答案
这里是networkx
的方法
import networkx as nx
G=nx.from_pandas_edgelist(df, 'CHILD', 'PARENT')
l=list(nx.connected_components(G))
L=[dict.fromkeys(y,x) for x, y in enumerate(l)]
d={k: v for d in L for k, v in d.items()}
df.groupby(df.CHILD.map(d)).agg({'CHILD':'unique','PARENT':'max'})
Out[328]:
PARENT CHILD
CHILD
0 4 [1, 2, 3]
1 12 [10, 11]
这篇关于在 pandas 数据框中创建父子对字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文