更改不在索引列表中的 NumPy 数组的值
问题描述:
我有一个 NumPy 数组,例如:
I have a NumPy array like:
a = np.arange(30)
我知道我可以使用例如花式索引替换位于 indices=[2,3,4]
位置的值:
I know that I can replace the values located at positions indices=[2,3,4]
using for instance fancy indexing:
a[indices] = 999
但是如何替换不在indices
中的位置的值呢?会像下面这样吗?
But how to replace the values at the positions that are not in indices
? Would be something like below?
a[ not in indices ] = 888
答
我不知道有什么干净的方法来做这样的事情:
I don't know of a clean way to do something like this:
mask = np.ones(a.shape,dtype=bool) #np.ones_like(a,dtype=bool)
mask[indices] = False
a[~mask] = 999
a[mask] = 888
当然,如果您更喜欢使用 numpy 数据类型,则可以使用 dtype=np.bool_
-- 输出不会有任何区别.这真的只是一个偏好问题.
Of course, if you prefer to use the numpy data-type, you could use dtype=np.bool_
-- There won't be any difference in the output. it's just a matter of preference really.