Python 熊猫:基于行上的交点创建列id
我有一个熊猫数据框,如下所示: id1 id2 id3 A. x U A. Y J B x T C Z R D P R 用于可能传递2列到的unpivot和用于DICIARY的get all,最后用于新列:Python 熊猫:基于行上的交点创建列id,python,pandas,Python,Pandas,我有一个熊猫数据框,如下所示: id1 id2 id3 A. x U A. Y J B x T C Z R D P R 用于可能传递2列到的unpivot和用于DICIARY的get all,最后用于新列: df1 = df.melt(id_vars='id1', value_vars=['id2','id3']) import networkx as nx # Create the graph from the dataframe g = nx.Graph() g = nx.from_pa
df1 = df.melt(id_vars='id1', value_vars=['id2','id3'])
import networkx as nx
# Create the graph from the dataframe
g = nx.Graph()
g = nx.from_pandas_edgelist(df1,'id1','value')
connected_components = nx.connected_components(g)
# Find the component id of the nodes
node2id = {}
for cid, component in enumerate(connected_components):
for node in component:
node2id[node] = cid + 1
df['g'] = df['id1'].map(node2id)
print (df)
id1 id2 id3 g
0 a x u 1
1 a y j 1
2 b x t 1
3 c z r 2
4 d p r 2