How to understand the np.argwhere function?

Viewed 2976
Signature: np.argwhere(a)
Docstring:
Find the indices of array elements that are non-zero, grouped by element.

Examples

>>> x = np.arange(6).reshape(2,3)
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.argwhere(x>1)
array([[0, 2],
       [1, 0],
       [1, 1],
       [1, 2]])

What does it mean by 'non-zero' and 'grouped by element'? and what is "x>1"?

2 Answers

In each row the first entry is the row index and the second entry is the column index of the entries of x that satisfy the condition.

For example: 2 is greater than 1 so the first row of argwhere gives you [0, 2] pointing to the position of 2 in x.

Find the indices (positions) of array elements that are non-zero (true), grouped by element (each index is its own row).

Basically, if you pass a boolean array, you will find the indices where that array is true, but transposed so that the indices in the form [[x1, x2, ...], [y1, y2, ...]] become in the form [[x1, y1], [x2, y2], ...].

x > 1 is a boolean array which is True wherever x > 1 and False wherever x <= 1. In your example, it looks loke

[[False, False, True],
 [True,  True,  True]]
Related