How to Use np.argwhere in NumPy: Syntax and Examples
Use
np.argwhere to find the indices of elements in a NumPy array that meet a condition. It returns a 2D array where each row is the index of a matching element. This is useful for locating positions of elements that satisfy a boolean expression.Syntax
The basic syntax of np.argwhere is:
np.argwhere(condition)
Here, condition is a boolean array or expression applied to a NumPy array. The function returns a 2D array of indices where the condition is True.
python
np.argwhere(a > 0)Example
This example shows how to use np.argwhere to find indices of elements greater than 3 in a 2D array.
python
import numpy as np a = np.array([[1, 4, 2], [3, 5, 0]]) indices = np.argwhere(a > 3) print(indices)
Output
[[0 1]
[1 1]]
Common Pitfalls
One common mistake is expecting np.argwhere to return a flat list of indices for 1D arrays. Instead, it always returns a 2D array of indices, where each row is a coordinate. For 1D arrays, you may want to flatten the result using .flatten() or use np.where for simpler output.
Also, passing a non-boolean array or incorrect condition will cause errors or unexpected results.
python
import numpy as np arr = np.array([10, 20, 30, 40]) # Wrong: expecting flat indices directly wrong_indices = np.argwhere(arr > 15) print(wrong_indices) # Output is 2D # Right: flatten to get 1D indices right_indices = np.argwhere(arr > 15).flatten() print(right_indices) # Alternative: use np.where for 1D arrays where_indices = np.where(arr > 15)[0] print(where_indices)
Output
[[1]
[2]
[3]]
[1 2 3]
[1 2 3]
Quick Reference
| Function | Description |
|---|---|
| np.argwhere(condition) | Returns 2D array of indices where condition is True |
| np.argwhere(condition).flatten() | Flattens indices to 1D array (useful for 1D arrays) |
| np.where(condition) | Returns tuple of arrays of indices, often simpler for 1D arrays |
Key Takeaways
np.argwhere returns a 2D array of indices where the condition is True.
For 1D arrays, flatten the result or use np.where for simpler index lists.
Always pass a boolean condition to np.argwhere to avoid errors.
np.argwhere is useful for locating positions of elements matching any condition in multi-dimensional arrays.