从python中的稀疏矩阵列出非零元素

如何以简单的单行代码(和快速!)列出csr_matrix的所有非零元素?

我正在使用此代码:

edges_list = list([tuple(row) for row in np.transpose(A.nonzero())])
weight_list = [A[e] for e in edges_list]

但执行需要相当长的时间.

最佳答案 对于规范形式的CSR矩阵,直接访问数据数组:

A.data

但请注意,不是规范形式的矩阵可能在其表示中包含明确的零或重复条目,这将需要特殊处理.例如,

# Merge duplicates and remove explicit zeros. Both operations modify A.
# We sum duplicates first because they might sum to zero - for example,
# if a 5 and a -5 are in the same spot, we have to sum them to 0 and then remove the 0.
A.sum_duplicates()
A.eliminate_zeros()

# Now use A.data
do_whatever_with(A.data)
点赞