I have a binary N-by-N (N~=200) NumPy array populated with zeroes and ones. I would like to apply a Boolean mask and 'swap' the values that correspond to True in the mask, so for example if I had:
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],
I would like the resulting array to be:
arr_new = np.array([1,0,0,1],
[1,0,0,1],
[1,0,0,1],
[1,0,0,1])
I started this by initially creating a function swap_cell that swaps between the values, and then followed the approaches in 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)
This code returns ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(), which I understand is because of the 'if' statement in my swap_cell() function. I know there must be a much more pythonic way to accomplish this, but I thought this might work.