You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于DataFrame中的另一列创建AreaID的network plot?

如何基于DataFrame生成Area-ID关联的网络图

这个需求其实很典型,核心思路是把同一个project-ID下的所有Area-ID两两配对——毕竟同一个项目里的区域肯定是有关联的,这样就能构建出区域之间的关联边。我常用Python的pandas、networkx和matplotlib来实现这类需求,步骤非常清晰:

步骤1:准备示例数据

先把你给出的DataFrame用pandas创建出来:

import pandas as pd

data = {
    'project-ID': [1, 1, 1, 2, 2, 2],
    'Area-ID': [2, 3, 5, 4, 2, 3]
}
df = pd.DataFrame(data)

步骤2:生成Area-ID的关联边

我们需要对每个project,提取对应的Area列表,然后生成所有两两组合的边。这里用itertools.combinations生成无重复的配对(比如(2,3)和(3,2)只保留一条,因为是无向关联):

from itertools import combinations

# 按project分组,生成每个组内Area的两两组合
edges = df.groupby('project-ID')['Area-ID'].apply(
    lambda x: list(combinations(x, 2))
).explode().tolist()

# 如果需要统计边的权重(两个Area共同出现的项目数),可以用Counter
from collections import Counter
edge_weights = Counter(edges)

步骤3:构建网络图并可视化

用networkx创建无向图,添加节点和带权重的边,然后画图:

import networkx as nx
import matplotlib.pyplot as plt

# 创建无向图
G = nx.Graph()

# 添加所有Area节点
G.add_nodes_from(df['Area-ID'].unique())

# 添加带权重的边:权重是两个Area共同出现的项目数
for edge, weight in edge_weights.items():
    G.add_edge(edge[0], edge[1], weight=weight)

# 设置画图参数:边的粗细根据权重调整
pos = nx.spring_layout(G, seed=42)  # seed保证布局固定
edge_width = [G[u][v]['weight'] * 2 for u, v in G.edges()]

# 画图
nx.draw_networkx_nodes(G, pos, node_size=1500, node_color='lightblue')
nx.draw_networkx_labels(G, pos, font_size=12, font_weight='bold')
nx.draw_networkx_edges(G, pos, width=edge_width, edge_color='gray')

# 显示边的权重(可选)
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

plt.title('Area-ID关联网络图(边粗细表示共同项目数)')
plt.axis('off')
plt.show()

效果说明

运行这段代码后,你会看到:

  • 节点是所有出现过的Area-ID(2、3、4、5)
  • 2和3之间的边最粗,因为它们同时出现在project1和project2里(权重2)
  • 2和5、3和5只在project1出现(权重1)
  • 2和4、3和4只在project2出现(权重1)

这样就完美展示了Area之间的关联强度,同一个项目下的区域都会被连接起来,边的粗细还能体现关联的紧密程度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:29:20