brews
brews

Reputation: 671

Alternative to using 'in' with numpy.where()

Lets say I have an array, 'foo', with two columns. Column 0 has values 1 to 12 indicating months. Column 1 has the corresponding measurement values. If I wanted to create a mask of measurement values from December, January and February (12,1,2) I would suspect that I could:

numpy.where(foo[:,1] in (12, 1, 2), False, True)

But it would appear that my clever 'in (12, 1, 2)' doesn't work as a conditional for where(). Nor does it appear to work as [12, 1, 2], etc...

Is there another clever way to do this? Is there a better way for me to collect all of the (12, 1, 2) measurements into an array? What is the numpy way?

(Reshaping the array is out of the question because there are an irregular number of measurements for each month)

Upvotes: 2

Views: 1127

Answers (1)

joris
joris

Reputation: 139222

I think the reason the 'in (12, 1, 2)' does not work is that the element before the 'in' has to be a single element.

But for this, numpy has the function in1d (documentation) to do a 'in' with a numpy array. With your code:

np.where(np.in1d(foo[:,0], [12, 1, 2]), False, True)

To complete the answer with the comment: in this case using where is redundant, the output of in1d can be used to index foo:

foo[np.in1d(foo[:,0], [12, 1, 2])]

or for

foo[~np.in1d(foo[:,0], [12, 1, 2])]

Note: in1d is only available from numpy 1.4 or higher.

Upvotes: 4

Related Questions