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]})
# Array dimension
l = len(df.columns)
# empty matrice
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
以Tai's solution为基础, 您可以使用
它产生了
^{pr2}$邻接矩阵的数据帧
您可以迭代数据帧以创建numpy数组:
array([[ 0., 1., 2.], [ 1., 0., 3.], [ 2., 3., 0.]])
numpy邻接矩阵的Networkx图
^{pr2}$[输出]:
EdgeDataView([(0, 1, {'weight': 1.0}), (0, 2, {'weight': 2.0}), (1, 2, {'weight': 3.0})])
而不是使用边缘列表表单
您还可以计算共现/邻接矩阵来表示您感兴趣的关系。它可以用点积构造。阿尔科已经在《熊猫》杂志上给出了答案
我用
^{pr2}$numpy
修改alko的答案我不喜欢alko的答案之一是它试图通过改变}返回一个副本,而有时返回一个视图。有关详细信息,请参阅我前面的问题Will changes in DataFrame.values always modify the values in the data frame?。在
df.values
来改变数据帧的对角线部分,比如df
。不应升级直接更改df.values
以更改df
,因为有时{如果想要遵循alko的pandas方法,可以用
df = df - np.eye(len(df)) * np.diagonal(df)
相关问题 更多 >
编程相关推荐