I have a two dimensional numpy array and I am using python 3.5. I am starting to learn about Boolean indexing which is way cool. I can do this with my two dimensional array, arr. mask = arr > 127 arr[mask] = 0
This works perfect but now I am trying to change this logic to use boolean indexing
for x in range(arr.shape[0]):
for y in range(arr.shape[1]):
if arr[x,y] < -10:
arr[x,y] = 0
elif arr[x,y] < 15:
arr[x,y] = arr[x,y] + 5
else:
arr[x,y] = 30
I tried multiple conditional operators for my indexing but I get the following error:
ValueError: boolean index array should have 1 dimension boolean index array should have 1 dimension.
I tried multiple versions to try to get this to work. Here is one try that produced the ValueError.
arr_temp = arr.copy()
mask = arry_temp < -10
mask2 = arry_temp < 15
mask3 = mask ^ mask3
arr[mask] = 0
arr[mask3] = arry[mask3] + 5
arry[~mask2] = 30
I received the error on mask3. I am new to this so I know the code above is not efficient trying to work out it.
Any tips would be appreciated.
This might help. Consider a numpy array of floating point values foo.
import numpy as np
foo=np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])
foo yields
array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8, 0.8])
This is how you get the values in foo > 0.3
foo[np.where( foo > 0.3)]
yields
array([0.4, 0.5, 0.6, 0.7, 0.8])
This is how to do the same with multiple conditions. In this case, values > 0.3 and less than 0.6.
foo[np.logical_and(foo > 0.3, foo < 0.6)]
yields
array([0.4, 0.5])
Alternatively using boolean mask array
mask_1 = foo > 0.3
mask_2 = foo < 0.6
mask_3 = np.logical_and(mask_1, mask_2)
mask_3
Yields a boolean mask array
array([False, False, False, True, True, False])
Which you can then use to slice the array via
foo[mask_3]
Yields
array([0.4, 0.5])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With