Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - Creating dictionary of parent child pairs in pandas dataframe

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]

I have been able to extract 12 and 4 as top parents from this dataframe, by code from following link:

extract column value based on another column pandas dataframe

Now, I have no idea how to do this in python. In java I can do this by following a dfs. Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the way from 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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...