Fab*_*nna 6 python numpy scipy
我正在阅读一个加权 egdelist / numpy 数组,如:
0 1 1
0 2 1
1 2 1
1 0 1
2 1 4
Run Code Online (Sandbox Code Playgroud)
其中列是“User1”、“User2”、“Weight”。我想用 执行 DFS 算法scipy.sparse.csgraph.depth_first_tree,它需要一个 N x N 矩阵作为输入。如何将上一个列表转换为方阵:
0 1 1
1 0 1
0 4 0
Run Code Online (Sandbox Code Playgroud)
在 numpy 或 scipy 中?
谢谢你的帮助。
编辑:
我一直在使用一个巨大的(1.5 亿个节点)网络,所以我正在寻找一种内存高效的方法来做到这一点。
您可以使用内存高效的scipy.sparse 矩阵:
import numpy as np
import scipy.sparse as sparse
arr = np.array([[0, 1, 1],
[0, 2, 1],
[1, 2, 1],
[1, 0, 1],
[2, 1, 4]])
shape = tuple(arr.max(axis=0)[:2]+1)
coo = sparse.coo_matrix((arr[:, 2], (arr[:, 0], arr[:, 1])), shape=shape,
dtype=arr.dtype)
print(repr(coo))
# <3x3 sparse matrix of type '<type 'numpy.int64'>'
# with 5 stored elements in COOrdinate format>
Run Code Online (Sandbox Code Playgroud)
要将稀疏矩阵转换为密集的 numpy 数组,您可以使用todense:
print(coo.todense())
# [[0 1 1]
# [1 0 1]
# [0 4 0]]
Run Code Online (Sandbox Code Playgroud)