基于NetworkX计算网络节点同类型邻居占比F1及均值F2的方法
完整实现代码
1. 预操作:给图节点补充属性
你之前的代码仅导入了边结构,没有关联节点的P属性,第一步先补全这部分,假设你的节点属性存储在node_df(含N、P两列)中:
import pandas as pd import networkx as nx from fractions import Fraction # 如需输出分数格式可导入该库 # 节点属性转字典 node_attr = node_df.set_index('N')['P'].to_dict() # 给图节点绑定P属性 nx.set_node_attributes(G, node_attr, name='P')
2. 计算F1值(同属性邻居占比)
f1_dict = {} for node in G.nodes: # 取当前节点自身的P属性 self_p = G.nodes[node]['P'] # 取所有邻居 neighbors = list(G.neighbors(node)) total_neighbor = len(neighbors) if total_neighbor == 0: f1_dict[node] = 0 continue # 统计同属性邻居数量 same_p_count = sum(1 for n in neighbors if G.nodes[n]['P'] == self_p) # 计算占比,要小数直接改 same_p_count / total_neighbor f1_dict[node] = Fraction(same_p_count, total_neighbor) # 转DataFrame输出 f1_df = pd.DataFrame(f1_dict.items(), columns=['N', 'F1']) print(f1_df)
3. 计算F2值(P=A邻居的F1均值)
f2_dict = {} for node in G.nodes: # 筛选所有P=A的邻居 a_neighbors = [n for n in G.neighbors(node) if G.nodes[n]['P'] == 'A'] if not a_neighbors: f2_dict[node] = None continue a_f1_list = [f1_dict[n] for n in a_neighbors] # 求均值,要保留所有F1值直接赋值 a_f1_list 即可,匹配示例中节点3的输出形式 f2_dict[node] = sum(a_f1_list) / len(a_f1_list) # 转DataFrame输出 f2_df = pd.DataFrame(f2_dict.items(), columns=['N', 'F2']) print(f2_df)
内容的提问来源于stack exchange,提问作者Math
相关产品推荐
相关产品推荐

