Python 有效地从numpy矩阵中获取值

Python 有效地从numpy矩阵中获取值,python,numpy,array-broadcasting,Python,Numpy,Array Broadcasting,我有一个矩阵:a=np.random.randn(10,3),位置:locs=[[6,6,0],[7,0,5],[0,9,2]。 我需要用占位符(例如0或np.inf)替换a第一列中loc第一列所述位置处的值。同样,必须用占位符替换a中loc第二列描述的位置 我目前已将其编写为循环: for i in range(0, locs.shape[1]): l = locs[:, i] current = a[:, i] current[l] = 0 a[:, i] =

我有一个矩阵:
a=np.random.randn(10,3)
,位置:
locs=[[6,6,0],[7,0,5],[0,9,2]
。 我需要用占位符(例如
0
np.inf
)替换
a
第一列中
loc
第一列所述位置处的值。同样,必须用占位符替换
a
loc
第二列描述的位置

我目前已将其编写为循环:

for i in range(0, locs.shape[1]):
    l = locs[:, i]
    current = a[:, i]
    current[l] = 0
    a[:, i] = current
是否可以用直接numpy操作替换此循环

输入示例:

a = 
[[ 1.43734578  0.09736638 -2.25746086]
 [-0.76353825  0.29902121 -0.47547664]
 [-0.6702289  -1.03620696  1.29729398]
 [-0.01606927  0.03169479  0.32413694]
 [-0.87992136 -0.13887237  0.76943651]
 [-0.99176294  1.2174871  -0.04219437]
 [-1.28379798 -2.05605769  0.30146702]
 [-0.7249709   0.12472804  0.43728411]
 [ 0.04843567  0.85251779 -0.12717516]
 [ 0.13927597  2.06447447 -0.74675081]]
预期产出为:

output = 
array([[ 0.        ,  0.        ,  0.        ],
       [-0.76353825,  0.29902121, -0.47547664],
       [-0.6702289 , -1.03620696,  0.        ],
       [-0.01606927,  0.03169479,  0.32413694],
       [-0.87992136, -0.13887237,  0.76943651],
       [-0.99176294,  1.2174871 ,  0.        ],
       [ 0.        ,  0.        ,  0.30146702],
       [ 0.        ,  0.12472804,  0.43728411],
       [ 0.04843567,  0.85251779, -0.12717516],
       [ 0.13927597,  0.        , -0.74675081]])

花式索引应该在这里起作用:

a[loc,np.arange(3)] = placeholder
例如:

>>> rng = np.random.default_rng()
>>> a = np.arange(30).reshape(10,3)
>>> b = rng.integers(0,10,(3,3))
>>> b
array([[1, 3, 4],
       [5, 7, 1],
       [1, 7, 9]])
>>> a[b,np.arange(3)] = 100
>>> a
array([[  0,   1,   2],
       [100,   4, 100],
       [  6,   7,   8],
       [  9, 100,  11],
       [ 12,  13, 100],
       [100,  16,  17],
       [ 18,  19,  20],
       [ 21, 100,  23],
       [ 24,  25,  26],
       [ 27,  28, 100]])
>>> rng = np.random.default_rng()
>>> a = np.arange(30).reshape(10,3)
>>> b = rng.integers(0,10,(3,3))
>>> b
array([[1, 3, 4],
       [5, 7, 1],
       [1, 7, 9]])
>>> a[b,np.arange(3)] = 100
>>> a
array([[  0,   1,   2],
       [100,   4, 100],
       [  6,   7,   8],
       [  9, 100,  11],
       [ 12,  13, 100],
       [100,  16,  17],
       [ 18,  19,  20],
       [ 21, 100,  23],
       [ 24,  25,  26],
       [ 27,  28, 100]])