HOW TO USE SEARCH IN NUMPY ARRAYS?

The where() method is used to search the certain value in an array and return the indexes that get a match.

import numpy as np

arr = np.array([3, 2, 3, 4, 3, 6, 7])

x = np.where(arr == 3)

print(x)

Output-

(array([0, 2, 4]),)

Search Sorted-

The searchsorted() method performs a binary search in the sorted array, and returns the index where the specified value would be inserted to maintain the search order.

import numpy as np

arr = np.array([1, 2, 3, 4])

x = np.searchsorted(arr, 3)

y = np.searchsorted(arr, 3, side='right')

z = np.searchsorted(arr, [2,3,4], side='right')
print(x)
print(y)
print(z)

Output-

2
3
[2 3 4]

Explanation-

np.searchsorted(arr, 3) – The number 3 should be inserted on index 2 to remain the sort order.

The method starts the search from the left and returns the first index where the number 3 is no longer larger than the next value.

np.searchsorted(arr, 3, side=’right’) -The method starts the search from the right and returns the first index where the number 3 is no longer less than the next value.

np.searchsorted(arr, [2,3,4], side=’right’) – We can also provide multiple values by passing array. It will find the indexes where the values 2, 3, and 4 should be inserted


Posted

in

Tags:

Comments

Leave a Reply