Searching within NumPy arrays is essential for filtering, locating elements, or conditional extraction. NumPy provides several useful functions to perform searches efficiently.
np.where(condition, [x, y])
— Returns indices or chooses values based on condition.np.argmax()
— Returns the index of the maximum value.np.argmin()
— Returns the index of the minimum value.np.nonzero()
— Returns indices of non-zero elements.np.flatnonzero()
— Returns indices of non-zero elements, flattened.np.searchsorted()
— Finds indices to insert elements in sorted arrays.import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60, 70, 80])
# 1. np.where(): Find indices where condition is true
indices = np.where(arr > 35)
print("Indices where arr > 35:", indices)
# Output: (array([3, 4, 5, 6, 7]),)
# 2. np.where() with x, y parameters: Conditional replacement
new_arr = np.where(arr > 35, arr, 0)
print("Elements > 35 kept, others replaced by 0:", new_arr)
# Output: [ 0 0 0 40 50 60 70 80]
# 3. np.argmax() and np.argmin(): Index of max/min
max_index = np.argmax(arr)
min_index = np.argmin(arr)
print("Index of max value:", max_index) # 7
print("Index of min value:", min_index) # 0
# 4. np.nonzero(): Indices of non-zero elements
arr2 = np.array([0, 1, 0, 2, 3, 0])
nonzero_indices = np.nonzero(arr2)
print("Indices of non-zero elements:", nonzero_indices)
# Output: (array([1, 3, 4]),)
# 5. np.flatnonzero(): Flattened indices of non-zero elements
flat_nonzero = np.flatnonzero(arr2)
print("Flat non-zero indices:", flat_nonzero)
# Output: [1 3 4]
# 6. np.searchsorted(): Find insertion points to maintain order
sorted_arr = np.array([10, 20, 30, 40, 50])
insert_pos = np.searchsorted(sorted_arr, 35)
print("Position to insert 35:", insert_pos) # 3
np.where(condition)
returns a tuple of arrays (one for each dimension) with indices satisfying the condition.np.searchsorted()
only on sorted arrays to find insertion points efficiently.np.nonzero()
and np.flatnonzero()
are useful to find all positions where elements are non-zero or True.where
, argmax
, argmin
, nonzero
, and searchsorted
help with different search needs.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!