繁体   English   中英

在Python中更快地计算矩阵的非零项

[英]Compute Non Zero Entries of a Matrix Faster in Python

我想从矩阵中生成三个向量,总结其非零值。 值向量,行索引向量和列索引向量。

例如,如果W = [[0.2。0.],[0.10。0.],[0。0. 5.]]。 我希望函数返回([2.0,10.0,5.0],[0,1,2],[1,1,2])。

下面的代码完成了这项工作,但对于大型矩阵来说太慢了。 我的工作量大约为100000.我不知道哪些索引不为零。 有没有办法加快速度?

from __future__ import division

import numpy as np
import collections
from numpy import *
import copy
#import timing



def nonZeroIndexes(W):
    s = W.shape
    nRows = s[0]
    nColumns = s[1]

    values = []
    row_indexes = []
    column_indexes = []

    for r in xrange(nRows):
        for c in xrange(nColumns):
            if W[r,c] != 0:
                values.append(W[r,c])
                row_indexes.append(r)
                column_indexes.append(c)
    return values, row_indexes, column_indexes

n = 3
W = np.zeros((n,n))

W[0,1] = 2
W[1,1] = 10
W[2,2] = 5

vecs = nonZeroIndexes(W)

使用np.nonzero

>>> import numpy as np
>>> W = np.array([[0, 2, 0], [0, 10, 0], [0, 0, 5]])
>>> 
>>> def nonZeroIndexes(W):
...     zero_pos = np.nonzero(W)
...     return (W[zero_pos],) + zero_pos
... 
>>> 
>>> nonZeroIndexes(W)
(array([ 2, 10,  5]), array([0, 1, 2]), array([1, 1, 2]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM