Python中级开发者求助:协议关系网络构建与节点中心性分析
监管方协议网络图解决方案
一、数据预处理
原始数据中单条协议包含多个参与方,需先拆分为两两配对的边数据,确保每个参与方组合对应一条协议边:
import pandas as pd from itertools import combinations # 读取你的原始数据(替换为实际读取方式) df = pd.read_csv("your_data.csv") df['PARTIES'] = df['PARTIES'].str.split(', ') # 生成所有参与方两两配对的边记录 edge_records = [] for _, row in df.iterrows(): parties = row['PARTIES'] # 生成当前协议下所有参与方的两两组合 for pair in combinations(parties, 2): edge_records.append({ "source": pair[0], "target": pair[1], "agreement_type": row['TYPE OF AGREEMENT'] }) edges_df = pd.DataFrame(edge_records)
二、构建网络图与中心性计算
使用networkx库构建网络并计算核心中心性指标,识别核心参与方:
import networkx as nx # 创建无向图(若协议为单向合作,可改为nx.DiGraph()) G = nx.from_pandas_edgelist(edges_df, source="source", target="target", edge_attr="agreement_type") # 计算三类常用中心性指标 degree_centrality = nx.degree_centrality(G) # 度中心性:衡量直接合作频次 betweenness_centrality = nx.betweenness_centrality(G) # 介数中心性:衡量作为合作枢纽的程度 closeness_centrality = nx.closeness_centrality(G) # 接近中心性:衡量连接其他节点的便捷度 # 整理中心性结果为DataFrame,方便排序查看 centrality_df = pd.DataFrame({ "party": list(G.nodes()), "degree_centrality": [degree_centrality[node] for node in G.nodes()], "betweenness_centrality": [betweenness_centrality[node] for node in G.nodes()], "closeness_centrality": [closeness_centrality[node] for node in G.nodes()] }) # 按度中心性降序查看核心参与方 print(centrality_df.sort_values("degree_centrality", ascending=False))
三、学术级可视化(边按协议类型配色)
结合matplotlib实现符合学术要求的精美网络图,边颜色随协议类型区分,节点大小关联中心性:
import matplotlib.pyplot as plt from matplotlib.patches import Patch # 定义协议类型与颜色的映射(可根据学术配色规范调整) color_map = { "Complex Agreement": "#1f77b4", "Crossfunctional Agreement": "#ff7f0e", # 新增协议类型时补充对应颜色 } # 获取每条边的颜色 edge_colors = [color_map[G[u][v]["agreement_type"]] for u, v in G.edges()] # 节点大小关联度中心性,核心节点更大 node_sizes = [degree_centrality[node] * 5000 for node in G.nodes()] # 设置绘图参数 plt.figure(figsize=(12, 8)) # 使用spring布局优化节点分布(k值控制间距,iterations控制布局迭代次数) pos = nx.spring_layout(G, k=0.15, iterations=20) # 绘制节点、边与标签 nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color="#e6f2ff", alpha=0.8) nx.draw_networkx_edges(G, pos, edge_color=edge_colors, width=2, alpha=0.6) nx.draw_networkx_labels(G, pos, font_size=10, font_weight="bold") # 添加协议类型图例 legend_elements = [Patch(facecolor=color, label=type_name) for type_name, color in color_map.items()] plt.legend(handles=legend_elements, loc="upper right", bbox_to_anchor=(1.2, 1)) # 美化图表 plt.title("Regulatory Party Agreement Network", fontsize=14, pad=20) plt.axis("off") plt.tight_layout() plt.show()
额外提示
- 若协议存在方向性(如A发起、B参与),将图类型改为
nx.DiGraph(),并调整可视化时的边样式(如添加箭头)。 - 中心性指标可按需选择:度中心性最直观反映合作频次,介数中心性适合识别网络枢纽节点。
- 配色可使用
seaborn的学术调色板(如sns.color_palette("colorblind")),提升图表专业性。
内容的提问来源于stack exchange,提问作者Fernando Luis Barroso da Silva
相关产品推荐
相关产品推荐

