numpy - 如何将 numpy 数组邻接列表转换为 numpy 数组邻接矩阵?
解决方案
您的数据或多或少的coo
格式,所以使用scipy.sparse.coo_matrix
构造函数。生成的稀疏矩阵可以转换为多种格式。
例子:
>>> from pprint import pprint
>>> import numpy as np
>>> from scipy import sparse
>>>
# create example
>>> a = np.random.randint(-10, 4, (10, 10)).clip(0, None) * 0.24
>>> a
array([[0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0.24, 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0.72, 0.24, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0.24, 0. , 0. , 0. , 0. ],
[0. , 0. , 0.24, 0. , 0.72, 0. , 0.48, 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.48, 0.24, 0. ],
[0. , 0. , 0. , 0.48, 0.48, 0. , 0. , 0.24, 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0.24, 0.48, 0. , 0. , 0.24],
[0. , 0.48, 0. , 0. , 0. , 0. , 0.72, 0. , 0. , 0.72],
[0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]])
>>>
# construct coo representation
>>> row, col = np.where(a)
>>> coo = np.rec.fromarrays([row, col, a[row, col]], names='row col value'.split())
>>> pprint(coo.tolist())
[(1, 2, 0.24),
(2, 0, 0.72),
(2, 1, 0.24),
(3, 5, 0.24),
(4, 2, 0.24),
(4, 4, 0.72),
(4, 6, 0.48),
(5, 7, 0.48),
(5, 8, 0.24),
(6, 3, 0.48),
(6, 4, 0.48),
(6, 7, 0.24),
(7, 5, 0.24),
(7, 6, 0.48),
(7, 9, 0.24),
(8, 1, 0.48),
(8, 6, 0.72),
(8, 9, 0.72)]
>>>
# create sparse matrix
>>> out = sparse.coo_matrix((coo['value'], (coo['row'], coo['col'])), (10, 10))
>>> out
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 18 stored elements in COOrdinate format>
>>>
# convert back to dense format
>>> out.A
array([[0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0.24, 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0.72, 0.24, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0.24, 0. , 0. , 0. , 0. ],
[0. , 0. , 0.24, 0. , 0.72, 0. , 0.48, 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.48, 0.24, 0. ],
[0. , 0. , 0. , 0.48, 0.48, 0. , 0. , 0.24, 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0.24, 0.48, 0. , 0. , 0.24],
[0. , 0.48, 0. , 0. , 0. , 0. , 0.72, 0. , 0. , 0.72],
[0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]])
推荐阅读
- forms - vue-electron-builder 插件 - 将表单数据从 vue 传递到主电子进程
- c# - 如何使用 Linq 选择所需的数据
- node.js - AWS sam SES sendEmail 导致 InvalidClientTokenId (nodejs/lambda)
- azure - 使用 Get-AzureStorageBlobContent 从 ADL Gen2 下载 parquet 文件
- linux - 如何在真实硬件上使用 LTP(Linux 测试项目)进行 Linux 内核测试?
- python - 如何在没有 numpy 或 pandas 的情况下从文本文件计算平均值
- javascript - 函数 slideToggle 仅检测 div 脚本的先前打开/关闭状态 javascript
- excel - 如何在 VBA 中使用 .numberformat 类型的变量作为比较器
- javascript - 如何使用 vanilla JS 或 CSS 以编程方式关闭 html 日期选择器?
- azure - 在 Cosmos DB 中计算限制