擅长:python、mysql、java
<h2>邻接矩阵的数据帧</h2>
<p>您可以迭代数据帧以创建numpy数组:</p>
<pre><code>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
</code></pre>
<p><code>array([[ 0., 1., 2.],
[ 1., 0., 3.],
[ 2., 3., 0.]])</code></p>
<h2>numpy邻接矩阵的Networkx图</h2>
^{pr2}$
<p>[输出]:<code>EdgeDataView([(0, 1, {'weight': 1.0}), (0, 2, {'weight': 2.0}), (1, 2, {'weight': 3.0})])</code></p>