NumPy Searching Arrays

🔍 NumPy Searching Arrays

Searching arrays means finding positions (indexes) of elements that match a condition or value.

NumPy provides useful methods:

where()
searchsorted()
argmax(), argmin()
nonzero()


 1. np.where() — Find Indexes of Matching Values


 

Output:

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

Meaning → Value 2 found at positions 1, 3, 5.


where() with Conditions


 

Output:

(array([2, 3]),)

👉 Useful Conditional Examples

ConditionCode
Find even numbersnp.where(arr % 2 == 0)
Find negative valuesnp.where(arr < 0)
Find specific rangenp.where((arr > 10) & (arr < 30))

 2. np.searchsorted() — Binary Search Index

Used when the array is sorted.


 

Output:

2

Meaning → 5 should be inserted at index 2 to keep array sorted.


 Search Multiple Values



 Search Right Position



 3. np.nonzero() — Find Non-Zero Elements


 

Output:

(array([1, 3, 4]),)

 4. Finding Maximum & Minimum Index


 

Output:

3
0

🔁 Searching in 2D Array


 

Output:

(array([0, 1]), array([1, 1]))

Meaning:

RowColumn
01
11

🧠 Summary Table

FunctionPurpose
where()Search elements based on value or condition
searchsorted()Find insert index in sorted array
nonzero()Find non-zero values
argmax()Find index of maximum value
argmin()Find index of minimum value

🎯 Practice Task


 

Find:
1. Indexes where value is 4
2. Index of max value
3. Index where 10 should be inserted (sorted order)

You may also like...