我有一个由0和1填充的二进制N乘N(N~=200)NumPyarray.我想要应用布尔掩码并‘交换’掩码中对应于True
的值,例如,如果我有:
arr = np.array([0,0,1,1],
[0,0,1,1],
[0,0,1,1],
[0,0,1,1])
mask = np.array([True,False,True,False],
[True,False,True,False],
[True,False,True,False],
[True,False,True,False],
我希望得到的数组是:
arr_new = np.array([1,0,0,1],
[1,0,0,1],
[1,0,0,1],
[1,0,0,1])
我首先创建了一个在值之间进行交换的函数swap_cell
,然后按照this answer中的方法进行操作.
def swap_cell(x):
if x == 1.0:
return 0.0
elif x == 0.0:
return 1.0
arr_new = np.where(mask,swap_cell(arr),arr)
这段代码返回ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
,我理解这是因为swap_cell()
函数中的‘if’语句.我知道一定有更多的方法来实现这一点,但我认为这可能会奏效.