首页 > 解决方案 > 如何将 numpy 数组邻接列表转换为 numpy 数组邻接矩阵?

问题描述

我在 numpy 数组中有一个下表。

在此处输入图像描述

现在我想把它转换成行为源、列为目标、值为权重的邻接矩阵。有人可以给我任何我可以利用的参考吗?

标签: numpyadjacency-matrixadjacency-list

解决方案


您的数据或多或少的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.  ]])

推荐阅读