Assign a group number to a particular set of values in pandas dataframe

Viewed 87

I have a dataframe as given below

data1=[202,701,410,301,402,201,202,301,310,210,302,302,401,402,601,303]
data2=[210,303,500,302,403,202,203,303,400,300,303,310,402,410,203,801]
df = pd.DataFrame(data1,columns = ['data1'])
df['data2'] = data2

which brings me the dataframe. Now I need to group the two columns with parent child relationship like below..

[201, 202, 203, 300, 210, 601],
[801, 301, 302, 303, 400, 310, 701],
[401, 402, 403, 500, 410]

I dont need the exact parent or exact child. I just want to group who all belong to same category in python 3.

Thanks in advance

1 Answers

Use networkx with connected_components, last convert output to list of lists:

import networkx as nx

# Create the graph from the dataframe
g = nx.Graph()
g.add_edges_from(df[['data1','data2']].itertuples(index=False))

Simplier is use convert_matrix.from_pandas_edgelist, thank you, @Dyz:

g = nx.from_pandas_edgelist(df,'data1','data2')

connected_components = nx.connected_components(g)

L = [list(x) for x in connected_components]
print (L)
[[201, 202, 203, 300, 210, 601], 
 [801, 301, 302, 303, 400, 310, 701], 
 [401, 402, 403, 500, 410]]
Related