将 Pandas 数据帧转换为邻接矩阵

时间:2021-01-10 15:00:43

标签: python pandas adjacency-matrix

我有一个 Pandas 数据框(930 行 × 50 列),如下所示:

<头>
index 关键字A 关键字B 关键字 c
第1页 1 3 1
第2页 4 0 2
第3页 0 1 1

我想将其转换为邻接矩阵/加权图,其中每个关键字都是一个节点。权重将是每个关键字之间的组合之和。

结果将是这样的:

<头>
关键字A 关键字B 关键字C
关键字A 0 3 8
关键字B 3 0 4
关键字C 8 4 0

1 个答案:

答案 0 :(得分:2)

解决方案看似简单:

adj = df.T @ df
np.fill_diagonal(adj.values, 0)

例如:

>>> df = pd.DataFrame([[1, 1, 3, 1], [2, 4, 0, 2], [3, 0, 1, 1]],
                      columns=["index", "A", "B", "C"]).set_index("index")
>>> df
       A  B  C
index
1      1  3  1
2      4  0  2
3      0  1  1
>>> adj = df.T @ df
>>> np.fill_diagonal(adj.values, 0)
>>> adj
   A  B  C
A  0  3  9
B  3  0  4
C  9  4  0
相关问题