ADVERTISEMENT
ADVERTISEMENT

NumPy - Searching

NumPy is a powerful library in Python that provides high-performance multidimensional array objects and tools for working with these arrays. It includes functions for performing complex mathematical operations, statistical functions, linear algebra functions, and many others.

Among the many tools that NumPy provides, there are several functions specifically designed for searching arrays. These include functions like argmax, argmin, where, and searchsorted.

1. argmax()

The argmax() function is used to find the indices of the maximum values along an axis. For example:

import numpy as np

# creating an array
arr = np.array([1, 2, 3, 10, 5, 6])

# Using argmax() function
index_of_max_value = np.argmax(arr)

print(index_of_max_value)  # Output: 3

In this case, argmax() returns 3, which is the index of the maximum value in the array.

2. argmin()

The argmin() function, on the other hand, is used to find the indices of the minimum values along an axis. Here's an example:

import numpy as np

# creating an array
arr = np.array([1, 2, 3, 10, 5, 6])

# Using argmin() function
index_of_min_value = np.argmin(arr)

print(index_of_min_value)  # Output: 0

In this case, argmin() returns 0, which is the index of the minimum value in the array.

3. where()

The where() function is used to return the indices of elements in an input array where the given condition is satisfied. It is one of the most commonly used functions for conditional checks and filtering of arrays. Here's an example:

import numpy as np

# creating an array
arr = np.array([1, 2, 3, 10, 5, 6])

# Using where() function to find indices of elements greater than 4
indices = np.where(arr > 4)

print(indices)  # Output: (array([3, 4, 5]),)

In this case, where() returns (array([3, 4, 5]),), which represents the indices of the elements in the array that are greater than 4.

4. searchsorted()

The searchsorted() function finds the indices into a sorted array arr such that, if the corresponding elements in v were inserted before the indices, the order of arr would be preserved. Here's an example:

import numpy as np

# creating a sorted array
arr = np.array([1, 3, 5, 7, 9])

# Using searchsorted() function to find indices where elements should be inserted to maintain the sorted order of array
indices = np.searchsorted(arr, [2, 4, 6])

print(indices)  # Output: [1 2 3]

In this case, searchsorted() returns [1 2 3]. This means that if we insert 2 at index 1, 4 at index 2, and 6 at index 3, the order of the array would be preserved.


ADVERTISEMENT

ADVERTISEMENT