如何对这个累积操作进行矢量化?

时间:2015-04-28 14:18:52

标签: python numpy

W成为维度(x, nP)的某个矩阵[请参阅问题末尾]

现在,我正在执行以下代码:

uUpperDraw = np.zeros(W.shape)
for p in np.arange(0, nP):
    uUpperDraw[s, p] = (W[s+1,:(p+1)]).sum()

我想对此进行矢量化以提高效率。给定pGrid = [0, 1, ...],我该如何重现以下内容?

uUpperDraw = np.array([sum(W[x, 0]), sum(W[x,0] + W[x, 1]), sum(W[x,0] + W[x, 1] + W[x, 2]) ...

这是一些可重复的例子。

>>> s, nP
(3, 10)
>>> W

array([[ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
         0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
         0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
         0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
         0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 2.        ,  1.63636364,  1.38461538,  1.2       ,  1.05882353,
         0.94736842,  0.85714286,  0.7826087 ,  0.72      ,  0.66666667]])
>>> uUpperDraw
array([[  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ],
       [  2.        ,   3.63636364,   5.02097902,   6.22097902,
          7.27980255,   8.22717097,   9.08431383,   9.86692252,
         10.58692252,  11.25358919],
       [  0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ,   0.        ,   0.        ,
          0.        ,   0.        ]])

1 个答案:

答案 0 :(得分:5)

这看起来像累计金额。当你想分别得到每一行的累积总和时,这就可以了。

uUpperDraw = np.cumsum(W,axis=1)