Use networkx
with connected_components
for dictionary created by minimal common values and then mapping to new column:
import networkx as nx
df1 = (df.melt('i_id')
.dropna(subset=['value'])
.groupby('i_id', as_index=False)['value'].min())
print (df1)
i_id value
0 1001 1001
1 1002 1001
2 1003 1001
3 1004 1001
4 1005 1001
5 1006 1003
6 1007 1003
7 1008 1003
8 1009 1007
9 1010 1007
10 1011 1011
11 1012 1012
12 1013 1013
13 1014 1014
# Create the graph from the dataframe
g = nx.Graph()
g = nx.from_pandas_edgelist(df1,'i_id','value')
connected_components = nx.connected_components(g)
# print (list(connected_components))
d = {y: min(x) for x in connected_components for y in x}
df['Key'] = df['i_id'].map(d)
print (df)
i_id g_id s_id p_id Key
0 1001 1001 1001 NaN 1001
1 1002 1001 1001 NaN 1001
2 1003 1001 1001 1003 1001
3 1004 1004 1001 1003 1001
4 1005 1004 1001 1003 1001
5 1006 1004 NaN 1003 1001
6 1007 1007 1007 1003 1001
7 1008 1007 1007 1003 1001
8 1009 1009 1007 NaN 1001
9 1010 1010 1007 NaN 1001
10 1011 1011 1011 1011 1011
11 1012 1012 1012 1012 1012
12 1013 1013 1013 1013 1013
13 1014 1014 1014 1014 1014
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…