我曾经看过以下代码段
import numpy as np
nx=3
ny=3
label = np.ones((nx, ny))
mask=np.zeros((nx,ny),dtype=np.bool)
label[mask]=0
生成的mask
是一个bool数组
[[False False False]
[False False False]
[False False False]]
如果我想将掩码中的一些元素分配给其他值,例如,我一直在尝试使用mask[2,1]="True"
,但是如果没有像我预期的那样更改corrsponding条目它就无法工作。获取访问权限和更改numpy数组的值的正确方法是什么。另外,label[mask]=0
做了什么?在我看来,它试图使用每个掩码条目值来指定相应的标签条目值。
答案 0 :(得分:0)
以下是一些代码段,其中包含一些可能有助于您理解这一点的注释。我建议你查看@Divakar提供的链接并查看boolean-indexing。
# a two dimensional array with random values
arr = np.random.random((5, 5))
# assign mask to a two dimensional array (same shape as arr)
# that has True for every element where the corresponding
# element in arr is greater than 0.5
mask = arr > 0.5
# assign all the elements in arr that are greater than 0.5 to 0
arr[mask] = 0
# the above can be more concisely written as:
arr[arr>0.5] = 0
# you can change the mask any way you want
# here I invert the mask
inv_mask = np.invert(mask)
# assign all the values in arr less than 0.5 to 1
arr[inv_mask] = 1