在numpy中向量化基于索引的矩阵运算

时间:2018-07-03 12:38:49

标签: python numpy vectorization

如何对以下循环进行矢量化处理?

def my_fnc():
   m = np.arange(27.).reshape((3,3,3))
   ret = np.empty_like(m)

   it = np.nditer(m, flags=['multi_index'])
   for x in it:
      i,j,k = it.multi_index
      ret[i,j,k] = x / m[i,j,i]
   return ret

基本上,我是将m中的每个值除以与对角线类似的东西。并非m中的所有值都会有所不同,范围只是一个例子。

谢谢!

PS::这是上面函数的输出,不要介意nans:)

array([[[        nan,         inf,         inf],
        [ 1.        ,  1.33333333,  1.66666667],
        [ 1.        ,  1.16666667,  1.33333333]],

       [[ 0.9       ,  1.        ,  1.1       ],
        [ 0.92307692,  1.        ,  1.07692308],
        [ 0.9375    ,  1.        ,  1.0625    ]],

       [[ 0.9       ,  0.95      ,  1.        ],
        [ 0.91304348,  0.95652174,  1.        ],
        [ 0.92307692,  0.96153846,  1.        ]]])

1 个答案:

答案 0 :(得分:2)

使用advanced-indexing一次性获得select moves.MoveItemCode, prd.PrdDescr, moves.MoveDate, SUM(MoveRealQty) as 'Purchased_Quantity' from Moves left join product on (moves.MoveItemCode=product.PrdCode) where (moves.MoveDate>'2018-06-01' and moves.MoveCase=2) group by moves.MoveItemCode,product.PrdDescr,moves.MoveDate order by moves.MoveItemCode asc,moves.MoveDate asc 等价物,然后简单地将输入数组除以它-

m[i,j,i]