لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.

# Python Data Science NumPy Searching Arrays

Searching Arrays

You can search an array for a certain value, and return the indexes that get a match.

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

Example 1: Find the indexes where the value is 14.

Code

import numpy as np

arr = np.array([11, 12, 13, 14, 15, 14, 14])

x = np.where(arr == 14)

print(x)

the output will be

(array([3, 5, 6], dtype=int64),)

The example above will return a tuple: (array([3, 5, 6],) Which means that the value 14 is present at index 3, 5, and 6.

Example 2: Find the indexes where the values are even.

Code

import numpy as np

arr = np.array([11, 12, 13, 14, 15, 16, 17, 18])

x = np.where(arr%2 == 0)

print(x)

the output will be

(array([1, 3, 5, 7], dtype=int64),)

Example 3: Find the indexes where the values are odd.

Code

import numpy as np

arr = np.array([11, 12, 13, 14, 15, 16, 17, 18])

x = np.where(arr%2 == 1)

print(x)

the output will be

(array([0, 2, 4, 6], dtype=int64),)

Search Sorted

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

The searchsorted() method is assumed to be used on sorted arrays.

Example 4: Find the indexes where the value 17 should be inserted.

Code

import numpy as np

arr = np.array([16, 17, 18, 19])

x = np.searchsorted(arr, 17)

print(x)

the output will be

1

Explanation: The number 17 should be inserted on index 1 to remain the sort order.
The method starts the search from the left and returns the first index where the number 7 is no longer larger than the next value.

Search From the Right Side

By default the left most index is returned, but we can give side='right' to return the right most index instead.

Example 5: Find the indexes where the value 17 should be inserted, starting from the right.

Code

import numpy as np

arr = np.array([16, 17, 18, 19])

x = np.searchsorted(arr, 17, side='right')

print(x)

the output will be

2

Explanation: The number 17 should be inserted on index 2 to remain the sort order.

The method starts the search from the right and returns the first index where the number 17 is no longer less than the next value.

Multiple Values

To search for more than one value, use an array with the specified values.

Example 6: Find the indexes where the values 12, 14, and 16 should be inserted.

Code

import numpy as np

arr = np.array([11, 13, 15, 17])

x = np.searchsorted(arr, [12, 14, 16])

print(x)

the output will be

[1 2 3]

Note: The return value is an array: [1 2 3] containing the three indexes where 12, 14, 16 would be inserted in the original array to maintain the order.