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_- 输出中没有任何差异.这只是一个偏好的问题.
仅适用于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)
| 归档时间: |
|
| 查看次数: |
21260 次 |
| 最近记录: |