NumPy Array Search

Search array

You can search (retrieve) a value in the array and then return the matching index obtained.

To search an array, please use where() method.

Example

Find the index of the value 4:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
print(x)

Run Instance

The above example will return a tuple:(array([3, 5, 6],

That means the value 4 appears at index 3, 5, and 6.

Example

Find the index of the value is even:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 0)
print(x)

Run Instance

Example

Find the index of the value is odd:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 1)
print(x)

Run Instance

search sorting

There is a name searchsorted() method, which performs a binary search in an array and returns the index where the specified value should be inserted to maintain the search order.

Assume searchsorted() The method is used for sorting arrays.

Example

Find the index where the value 7 should be inserted:

import numpy as np
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7)
print(x)

Run Instance

Example Explanation:The number 7 should be inserted at index 1 to maintain the sorted order.

This method searches from the left and returns the first index where the number 7 is no longer greater than the next value.

Search from the Right

By default, the leftmost index is returned, but we can specify side='right'to return the rightmost index.

Example

Search from the right to find the index where the value 7 should be inserted:

import numpy as np
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7, side='right')
print(x)

Run Instance

Example Explanation:The number 7 should be inserted at index 2 to maintain the sorted order.

This method searches from the right and returns the first index where the number 7 is no longer less than the next value.

Multiple Values

To search for multiple values, use an array with specified values.

Example

Find the indices where the values 2, 4, and 6 should be inserted:

import numpy as np
arr = np.array([1, 3, 5, 7])
x = np.searchsorted(arr, [2, 4, 6])
print(x)

Run Instance

The return value is an array:[1 2 3] Contains three indices, where 2, 4, and 6 will be inserted into the original array to maintain order.