Array Search in NumPy
NumPy Search Functions.
NumPy provides various ways to search for elements in an array. Here are some key methods:
Finding Indices of Elements
The np.where()
function returns the indices where a condition is met.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
# Find indices where elements are greater than 25
indices = np.where(arr > 25)
print(indices) # Output: (array([2, 3, 4]),)
# Getting actual values that satisfy the condition
print(arr[indices]) # Output: [30 40 50]
For 2D arrays:
matrix = np.array([[10, 20], [30, 40]])
# Find indices where elements are equal to 20
indices = np.where(matrix == 20)
print(indices) # Output: (array([0]), array([1]))
Searching for a Specific Element
np.argwhere()
returns the row and column indices where a condition is True
.
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(np.argwhere(arr == 5))
# Output: [[1 1]] -> (Row 1, Column 1)
Finding the Index of the First Occurrence
np.argmax()
: Returns the index of the maximum value.np.argmin()
: Returns the index of the minimum value.
arr = np.array([3, 1, 8, 2, 9, 5])
print(np.argmax(arr)) # Output: 4 (Index of max value: 9)
print(np.argmin(arr)) # Output: 1 (Index of min value: 1)
For 2D arrays:
matrix = np.array([[1, 2, 3], [7, 5, 6]])
print(np.argmax(matrix, axis=0)) # Column-wise max indices
print(np.argmax(matrix, axis=1)) # Row-wise max indices
Checking if a Value Exists
np.isin()
checks if elements exist in an array.
arr = np.array([10, 20, 30, 40])
print(np.isin(arr, [20, 50]))
# Output: [False True False False]
For 2D arrays:
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(np.isin(matrix, [2, 6]))
Output:
[[False True False]
[False False True]]
Finding Unique Elements
np.unique()
returns the unique elements in a sorted order.
arr = np.array([1, 2, 3, 2, 4, 1, 5])
print(np.unique(arr))
# Output: [1 2 3 4 5]
It can also return counts of unique elements:
unique_elements, counts = np.unique(arr, return_counts=True)
print(unique_elements) # [1 2 3 4 5]
print(counts) # [2 2 1 1 1]
NumPy Search Functions
Function | Purpose |
---|---|
np.where() | Find indices where a condition is met |
np.argwhere() | Find row/column indices of matching elements |
np.argmax() | Index of the maximum element |
np.argmin() | Index of the minimum element |
np.isin() | Check if elements exist in an array |
np.unique() | Find unique values in an array |
No questions available.