加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:04:44 所属栏目: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
如何以简单的单行代码(和快速!)列出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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读