Sunday, May 31, 2020

Numpy ndarray search

Searching the Numpy Arrays


where() method


Numpy array can be easily searched using where() method. This method returns all the index positions that pose a match.

import numpy as np

nums=np.array([16,11,22,12,16,42,17,55,12,12])
results=np.where(nums==12)
print(results)

#Output
(array([3, 8, 9]),)
This method returns a tuple, representing the indexes containing the value equal to 12.

Even, we can perform complex searches such as,

import numpy as np

nums=np.array([16,11,22,12,16,42,17,55,12,12])
results=np.where(nums>20) #binary condition
print(results)

#Output
(array([2, 5, 7]),)
OR

import numpy as np

nums=np.array([16,11,22,12,16,42,17,55,12,12])
results=np.where(nums%2==0) #binary condition
print(results) #Even numbers

#Output
(array([0, 2, 3, 4, 5, 8, 9]),)

searchsorted() method


This method is applied to sorted sequences, applies binary search, and returns the index position, where the item must be placed correctly to retain the sorted order.

import numpy as np

nums=np.array([16,11,22,12,16,42,17,55,12,12])
numssorted=np.sort(nums)
results=np.searchsorted(numssorted, 21) 
print(results)  #7

We can also search from right side of the array.

import numpy as np

nums=np.array([16,11,22,12,16,42,17,55,12,12])
numssorted=np.sort(nums)
results=np.searchsorted(numssorted, 21, side="right") 
print(results)  #7

We can also search for multiple values, for example

import numpy as np

nums=np.array([16,11,22,12,16,42,17,55,12,12])
numssorted=np.sort(nums)
results=np.searchsorted(numssorted, [21, 40, 85]) 
print(results)  

#Output
[ 7  8 10]
It means 21, 40, 85 can be inserted at 7,  8 , 10 positions respectively in the sorted array.