NumPy数组,更改索引列表中不存在的值

Sau*_*tro 33 python arrays replace numpy multidimensional-array

我有一个numpy像这样的数组:

a = np.arange(30)
Run Code Online (Sandbox Code Playgroud)

我知道我可以indices=[2,3,4]使用例如花式索引来替换位置上的值:

a[indices] = 999
Run Code Online (Sandbox Code Playgroud)

但是如何替换不在的位置的值indices?会是这样的吗?

a[ not in indices ] = 888
Run Code Online (Sandbox Code Playgroud)

谢谢!

mgi*_*son 45

我不知道干净的方法做这样的事情:

mask = np.ones(a.shape,dtype=bool) #np.ones_like(a,dtype=bool)
mask[indices] = False
a[~mask] = 999
a[mask] = 888
Run Code Online (Sandbox Code Playgroud)

当然,如果您更喜欢使用numpy数据类型,您可以使用dtype=np.bool_- 输出中没有任何差异.这只是一个偏好的问题.

  • 为什么不使用`np.ones_like` (4认同)
  • 另外,您可以通过一次调用`numpy.where`来替换最后几行(这是它真正有用的主要情况).例如`a = np.where(mask,888,999)`. (4认同)
  • @JoeKington - 我认为`a [...] = np.where(mask,888,999)`可能会覆盖`a`来演示Ellipsis运算符,而不是很多人都知道:) (3认同)

aar*_*ren 6

仅适用于1d数组:

a = np.arange(30)
indices = [2, 3, 4]

ia = np.indices(a.shape)

not_indices = np.setxor1d(ia, indices)
a[not_indices] = 888
Run Code Online (Sandbox Code Playgroud)