首页 > 解决方案 > 如何使用 numpy 更优雅地实现这个 for 循环?

问题描述

这是我的代码片段。有人可以采取适当的方式来做到这一点。一些花哨的 NumPy 技巧?

q_val = np.random.rand(5,3) 

action = np.ones((5,1),int)
to_set = np.ones((5,1),int)
for x in range(5):
     q_val[x][action[x]] -= to_set[x]

这就是我实例化值的方式

q_val = np.random.rand(5,3) //lets say the middel of randome
q_val = array([[0.93373647, 0.        , 0.14962181],//get only zeroes
       [0.67909199, 0.        , 0.07462584],
       [0.05696713, 0.        , 0.03221326],
       [0.78209394, 0.        , 0.58312439],
       [0.09217555, 0.        , 0.17876316]])                           
action = np.ones((5,1),int)
action = >>> action
array([[1],
       [1],
       [1],
       [1],
       [1]])

to_set = np.ones((5,1),int)
to_set = array([[1],
       [1],
       [1],
       [1],
       [1]])

这就是我要改变的

for x in range(5):
     q_val[x][action[x]] -= to_set[x]

这就是我会得到的

array([[ 0.93373647, -1.        ,  0.14962181],
       [ 0.67909199, -1.        ,  0.07462584],
       [ 0.05696713, -1.        ,  0.03221326],
       [ 0.78209394, -1.        ,  0.58312439],
       [ 0.09217555, -1.        ,  0.17876316]])

我确信有一些奇特的方法可以在其中一条线上做到这一点。有人可以帮忙吗?

标签: pythonpython-3.xnumpy

解决方案


您可以只使用数组来索引其他数组:

index = np.arange(len(action))
q_val[index, action] -= to_set[index]

推荐阅读