Python Numpy : Select elements or indices by conditions from Numpy Array

How to elect elements or indices by conditions from Numpy Array in Python ?

In this article we will see how we can select and print elements from a given Numpy array provided with multiple conditions.

Selecting elements from a Numpy array based on Single or Multiple Conditions :

When we apply a comparison operator to a numpy array it is applied to each & every elements of the array. It is seen that True or False will be returned as bool array accordingly when its elements satisfies the condition.

#Program :

import numpy as sc

# To create a numpy array from 2 to 25 with interval 23
num_arr = sc.arange(2, 25, 3)

# To compare with all elements in array
bool_arr = num_arr < 15
print(bool_arr)

Output :
[ True  True  True  True  True False False False]

If we pass the resulted bool Numpy array in [] operartor then it will form a new Numpy Array with elements which were found True in corresponding bool Numpy array.

#Program :

import numpy as sc

num_arr = sc.arange(2, 25, 3)
bool_arr = num_arr < 15
print(bool_arr)

# Those elements will be selected where it is True at corresponding value in bool array
new_arr = num_arr[bool_arr]
print(new_arr)
Output :
[ True  True  True  True  True False False False]
[ 2  5  8 11 14]

Select elements from Numpy Array which are divisible by 5 :

We can select and print those elements which are divisible by 5 from given Numpy array.

 

#Program :

import numpy as sc

# Numpy arrray with elements frrm 3 to 25
num_arr = sc.arange(3, 25, 1)

# To select those numbers which are divisible by 5
new_arr = num_arr[num_arr%5==0]

print(new_arr)
Output :
[ 5  10  15  20 ]

Select elements from Numpy Array which are greater than 10 and less than 18 :

We can select and print those elements which are smaller than 10 and greater than 18 from given Numpy array.

 

#Program :

import numpy as sc

# Numpy arrray with elements frrm 3 to 25
num_arr = sc.arange(3, 25, 1)

# To select those numbers which are greater than 10 and smaller than 18
new_arr = num_arr[(num_arr > 10) & (num_arr < 18)]

print(new_arr)
Output :
[11 12 13 14 15 16 17]