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:
Meaning → Value 2 found at positions 1, 3, 5.
where() with Conditions
Output:
👉 Useful Conditional Examples
| Condition | Code |
|---|---|
| Find even numbers | np.where(arr % 2 == 0) |
| Find negative values | np.where(arr < 0) |
| Find specific range | np.where((arr > 10) & (arr < 30)) |
2. np.searchsorted() — Binary Search Index
Used when the array is sorted.
Output:
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:
4. Finding Maximum & Minimum Index
Output:
🔁 Searching in 2D Array
Output:
Meaning:
| Row | Column |
|---|---|
| 0 | 1 |
| 1 | 1 |
🧠 Summary Table
| Function | Purpose |
|---|---|
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 |
