首页 > 解决方案 > 从图的边缘创建共现矩阵

问题描述

我有平行边(多条边)的图,如下所示

G=nx.read_edgelist('file.txt',create_using=nx.MultiGraph(), nodetype=int)

示例输出(1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (1, 4)

现在在这里我想从这个图中创建共现矩阵

示例输出

  1  2  3   4 
1 0  13 17  24
2 13 0
etc

我该怎么做?堆栈溢出的大多数解决方案都是针对单词共现的

任何帮助都感激不尽

标签: python-3.xmatrixgraph

解决方案


您可以使用Counter模块中的collections

from collections import Counter

G = ...
cocounts = Counter(list(G.edges()))

# Then just allocate a list (2x4) or something and create the matrix:
res = [[0 for c in range(4)] for r in range(2)]
for cocount, count in cocounts.items():
    res[cocount[0]-1][cocount[1]-1] = count

推荐阅读