Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy mask based on if a value is in some other list

Tags:

python

numpy

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...

like image 720
Joran Beasley Avatar asked Nov 29 '12 15:11

Joran Beasley


People also ask

How do you make a boolean mask in Python?

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.

What is masked array NumPy?

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.

How do you mask Nan values in Python?

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.


2 Answers

Use numpy.in1d():

In [6]: np.in1d(a, [14, 16, 18])
Out[6]: array([False, False, False,  True, False,  True, False], dtype=bool)
like image 63
NPE Avatar answered Sep 22 '22 08:09

NPE


Accepted answer is right but currently numpy's docs recommend using isin function instead of in1d

like image 38
sgt pepper Avatar answered Sep 22 '22 08:09

sgt pepper