I have searched high and low and just cant find a way to do it (Its possible i was searching for the wrong terms.)
I would like to create a mask (eg [True False False True True]) based on whether each value is in some other list.
a=np.array([11,12,13,14,15,16,17])
mask= a in [14,16,8] #(this doesnt work at all!)
#I would like to see [False False False True False True False]
so far the best i can come up with is a list comprehension
mask = [True if x in other_list else False for x in my_numpy_array]
please let me know if you know of some secret sauce to do this with numpy and fast (Computationally), as this list in reality is huge...
To create a boolean mask from an array, use the ma. make_mask() method in Python Numpy. The function can accept any sequence that is convertible to integers, or nomask. Does not require that contents must be 0s and 1s, values of 0 are interpreted as False, everything else as True.
A masked array is the combination of a standard numpy. ndarray and a mask. A mask is either nomask , indicating that no value of the associated array is invalid, or an array of booleans that determines for each element of the associated array whether the value is valid or not.
To mask an array where invalid values occur (NaNs or infs), use the numpy. ma. masked_invalid() method in Python Numpy. This function is a shortcut to masked_where, with condition = ~(np.
Use numpy.in1d()
:
In [6]: np.in1d(a, [14, 16, 18])
Out[6]: array([False, False, False, True, False, True, False], dtype=bool)
Accepted answer is right but currently numpy
's docs recommend using isin
function instead of in1d
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