In this article we will discuss how to select elements or indices from a Numpy array based on multiple conditions.


Similar to arithmetic operations when we apply any comparison operator to Numpy Array, then it will be applied to each element in the array and a new bool Numpy Array will be created with values True or False.
Suppose we have a Numpy Array i.e.

It’s contents are,

Let’s select elements from it.

Select elements from a Numpy array based on Single or Multiple Conditions

Let’s apply < operator on above created numpy array i.e.

Comparison Operator will be applied to each element in array and number of elements in returned bool Numpy Array will be same as original Numpy Array. But but for every element that satisfies the condition there will be True in array and False for Others in the returned array.
contents of boolArr are,

If we pass this bool Numpy Array to subscript operator [] of original array then it will returns a new Numpy Array containing elements from Original array for which there was True in bool Numpy Array i.e.

We can do all that in a single line by passing complete comparing expression in [] operator i.e.

Just like above, it will return a new Numpy Array with elements < 10 from original Numpy Array i.e.

Let’s checkout some other examples,

Select elements from Numpy Array which are divisible by 3 :

Contents of Numpy Array arr,

Now lets’ select elements from this Numpy array which are divisible by 3 i.e.

Contents of Numpy array newArr are,

Select elements from Numpy Array which are greater than 5 and less than 20:

Here we need to check two conditions i.e. element > 5 and element < 20. But python keywords and , or doesn’t works with bool Numpy Arrays. Instead of it we should use & , | operators i.e.

arr > 5 returns a bool numpy array and arr < 20 returns an another bool numpy array. Now applying & operator on both the bool Numpy Arrays will generate a new bool array newArr.

Contents of Numpy array newArr are,

Complete example is as follows,

Output

 

Click Here to Subscribe for more Articles / Tutorials like this.