我有一个像这样的 NumPy 数组:
a = np.arange(30)
我知道我可以使用例如花哨的索引替换位于 indices=[2,3,4]
位置的值:
a[indices] = 999
但是如何替换indices
中没有的位置的值呢?会像下面这样吗?
a[ not in indices ] = 888
最佳答案
我不知道有一种干净的方式来做这样的事情:
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_
-- 输出不会有任何差异。这只是一个偏好问题。
关于python - 更改不在索引列表中的 NumPy 数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16940895/