NumPy Searching Arrays

NumPy Searching Arrays

NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.

In this tutorial, we will give examples of how to search arrays with NumPy.

Searching Arrays

You can search an array using the where() function.
The where() function returns values that match a condition:

Syntax:

import numpy as np

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

Output:

(array([3, 5, 6]),)

The example above will return a tuple: (array([3, 5, 6]),)
The first array contains the indexes of the matched values.

Example:

import numpy as np

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

print(x)

Output:

(array([1, 3, 5, 7]),)

The example above will return tuple having the indexes of even numbers in the array.

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.

Syntax:

import numpy as np

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

print(x)

Output:

1

The example above returns the index of 7 which is 1 (because indexing starts from 0).

Example:

import numpy as np

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

print(x)

Output:

[1 2 3]

The example above returns an array with the indexes where the specified values can be inserted in the original array to maintain the order.

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.

Syntax:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 4])
x = np.searchsorted(arr, 4, side='right')

print(x)

Output:

8

The example above returns the index of the last 4.

Multiple Values

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

Syntax:

import numpy as np

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

print(x)

Output:

[1 2 3]

The example above returns an array with the indexes where the specified values can be inserted in the original array to maintain the order.

Conclusion

Numpy is a powerful library for working with multi-dimensional arrays and matrices in Python. In this tutorial, we learned how to use Numpy to search arrays for matching values, using functions such as where() and searchsorted(). We also learned how to search from the right side, and how to search for multiple values at once. These functions are useful for data analysis, and can make working with large data sets much easier and more efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *