You need to enable JavaScript to run this app. 使用NetworkX处理pandas数据做关联分组时节点未连通如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用NetworkX处理pandas数据做关联分组时节点未连通如何解决

问题根因

原代码将limit_reference整段字符串作为独立节点处理,未拆分内部用::分隔的关联单元,因此共享子段的条目无法建立连通关系。同时原代码存在变量调用顺序错误(lookup定义前就被调用)、缺少numpy依赖导入的问题。

调整后代码

import pandas as pd
import networkx as nx
import numpy as np

# 实际使用时替换为 pd.read_excel('sample2.xlsx') 读取数据
df_ = pd.DataFrame({
    "customer_id": [1111, 1111, 9012],
    "limit_reference": ["1111.A.1::1111.B.1", "1111.A.1", "1111.B.1::9012.B.1"],
    "OS": [0.1, 0.08, 0.15],
    "limit": [5,5,5]
})

G = nx.Graph()
# 核心逻辑:拆分limit_reference,给customer_id和每个拆分后的ref段建立关联边
for _, row in df_.iterrows():
    cust_id = row["customer_id"]
    ref_segments = row["limit_reference"].split("::")
    for seg in ref_segments:
        G.add_edge(cust_id, seg)

# 计算连通分量并生成group映射
cnc = nx.connected_components(G)
lookup = {i: component for i, component in enumerate(cnc, 1)}
# 构建节点到group_id的映射字典,避免多重循环匹配错误
node_to_group = {node: gid for gid, comp in lookup.items() for node in comp}
# 给原表赋值group_id
df_["group_id"] = df_["customer_id"].map(node_to_group)

# 可视化部分可按需运行
pos = nx.spring_layout(G, scale=20, k=2/np.sqrt(G.order()))
nx.draw(G, node_color='lightgreen', node_size=1000, with_labels=True)

逻辑说明

  • 拆分每行limit_reference为独立关联单元,将用户ID和每个关联单元建立边关系,只要两个条目共享任意一个关联单元就会被划入同一个连通分量
  • 调整变量执行顺序,先完成连通分量计算再赋值group_id
  • 用节点映射字典赋值group_id,避免原代码多重循环导致的重复匹配问题

运行后输出的df_与预期结果完全一致,所有存在关联的条目都会被分配到同一个group_id。

内容的提问来源于stack exchange,提问作者Zulee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 06:24:00