python-3.x - 从图的边缘创建共现矩阵
问题描述
我有平行边(多条边)的图,如下所示
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
我该怎么做?堆栈溢出的大多数解决方案都是针对单词共现的
任何帮助都感激不尽
解决方案
您可以使用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
推荐阅读
- python - 使用 App-Engine 和 Cloud Functions 的基于 Python 的 GCP 项目的推荐项目结构
- java - 应用程序启动方法中的异常。java.lang.reflect.InvocationTargetException javafx8
- javascript - 如何获取 id 和拼接选定数据?我使用了类星体框架
- python - csv文件输出新行
- ios - 当我在 UITableView 中更改 UITextField 的文本颜色时,滚动时颜色已应用于另一个 UITextfield
- regex - 八度正则表达式将字符字符串拆分为子字符串
- ios - Apple Porvisioning 和 Visual Studio 的问题
- python - python pandas平均列以产生新的
- python - Tensorflow 2.0:如何在特征层面实现融合网络?
- amazon-web-services - VS 2017 未能将容器发布到 AWS