Skip to content
Advertisement

Check equality of multiple elements in array

I’m new to Python from Matlab.

I want to create a new variable from a subset of an existing numpy array based on equality to some condition specified by a third numpy array, an ID in this case.

This works fine for one equality.

JavaScript

But if I try to extend it several equalities at once it no longer works:

JavaScript

Ideally I want to be able to choose many equalities, like:

JavaScript

I could loop through each number I want to check but is there a simpler way of doing this?

Advertisement

Answer

You could use np.isin + np.r_:

JavaScript

Output

JavaScript

You could substitute np.r_ by something like [1, 2, 7] and use it as below:

JavaScript

Additionally if the array is 1-dimensional you could use np.in1d:

JavaScript

Output (from in1d)

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement