一种pythonic方法,用于在具有0的2D numpy数组中屏蔽特定索引后的所有值
我有一个二维数组和一个一维索引数组,如下所示:一种pythonic方法,用于在具有0的2D numpy数组中屏蔽特定索引后的所有值,numpy,indexing,masking,Numpy,Indexing,Masking,我有一个二维数组和一个一维索引数组,如下所示: a = np.random.rand(2,5) a >>> a array([[0.70095892, 0.01068342, 0.69875872, 0.95125273, 0.18589609], [0.02990893, 0.78341353, 0.12445391, 0.71709479, 0.24082166]]) >>> ind array([3, 2]) 我希望索引3之后(包
a = np.random.rand(2,5)
a
>>> a
array([[0.70095892, 0.01068342, 0.69875872, 0.95125273, 0.18589609],
[0.02990893, 0.78341353, 0.12445391, 0.71709479, 0.24082166]])
>>> ind
array([3, 2])
我希望索引3之后(包括)第1行中的所有值变为0,索引2之后第2行中的所有值变为0。因此,最终输出为:
array([[0.70095892, 0.01068342, 0.69875872, 0, 0],
[0.02990893, 0.78341353, 0, 0, 0]])
你能帮我做这个吗?你可以通过:
您可以通过以下方式执行此操作:
import numpy as np
a = np.random.rand(2, 5)
ind = np.array([3, 2])
# create a boolean indexing matrix
bool_ind = np.arange(a.shape[1]) >= ind[:, None]
print(bool_ind)
# [[False False False True True]
# [False False True True True]]
# modify values in a using the boolean matrix
a[bool_ind] = 0
print(a)
# [[0.78594869 0.11185728 0.06070476 0. 0. ]
# [0.48258651 0.3223349 0. 0. 0. ]]