在 R 中,我可以基于数据框的两列创建网络,然后将其集群成员 ID 作为新的聚合列分配给原始数据框,如下所示。
library(igraph)
library(data.table)
g = graph_from_data_frame(df[, .(col1, col2)])
clu = clusters(g)
df[, cluId := clu$membership[as.character(df[, col1])]]
您将如何在 Python 中使用 pandas 和 igraph 或 networkx 执行相同的操作? 我在这里发现了一个类似的问题,但提供的答案很慢。
Assigning Group ID to components in networkx
例子:
请您参考如下方法:
import networkx as nx
# Create the graph from the dataframe
g = nx.Graph()
g.add_edges_from(df.itertuples(index=False))
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
现在 node2id 是一个将节点映射到其组件 ID 的字典。然后,您可以根据此字典生成一个列并将其添加到原始数据框中,如 michaelg's answer 中所示。 .
编辑
从数据框获取图形的更好方法:
g = nx.from_pandas_edgelist(df, 0, 1)
