将数据框转换为邻接矩阵
您可以遍历数据框以创建一个numpy数组:
import pandas as pd
import numpy as np
from itertools import combinations
import networkx as nx
df = pd.DataFrame({'node_1': [1,0,1,1,0],
'node_2':[0,1,0,1,1],
'node_3':[1,1,0,1,1]})
l = len(df.columns)
mat = np.zeros((l,l))
for i, row in df.iterrows():
positions = np.where(row)[0]
if len(positions)>1:
for comb in combinations(positions,2):
i,j = comb
mat[i,j] += 1
mat[j,i] += 1
mat
array([[ 0., 1., 2.],
[ 1., 0., 3.],
[ 2., 3., 0.]])
从Numpy邻接矩阵创建Networkx图
G = nx.Graph(mat)
G.edges(data=True)
[out]:
EdgeDataView([(0, 1, {'weight': 1.0}), (0, 2, {'weight': 2.0}), (1, 2, {'weight': 3.0})])
[out]:
EdgeDataView([(0, 1, {'权重': 1.0}), (0, 2, {'权重': 2.0}), (1, 2, {'权重': 3.0})])