np.argwhere: How to Use Numpy argwhere() Function

The np.argwhere() is the same as np.transpose(np.nonzero()). The argwhere() function’s output is unsuitable for indexing arrays. For this purpose, use nonzero (a) instead.

np.argwhere

The np.argwhere() is a numpy library function used to find the indices of nonzero array elements grouped by element. The numpy argwhere() function takes an array-like parameter and returns the indices of the array elements.

Syntax

numpy.argwhere(a)

Parameters

The np argwhere() function takes one parameter a whose data type is array_like.

Example

First, we will import the numpy library and then define the data. Then we will use the np argwhere() function to find the indices of nonzero elements.

# app.py

import numpy as np

data = [[ 11, 0, 21], [0, 19, 18]]
print(data)
nonZeroIndices = np.argwhere(data)
print(nonZeroIndices)

Output

python3 app.py
[[11, 0, 21], [0, 19, 18]]
[[0 0]
 [0 2]
 [1 1]
 [1 2]]

In the above code, 11 is not zero, and its index is [0, 0] means on the 0 rows and 0 column, 11 element is there. So it returns [0 ,0]. Same for 21 element whose index is [0, 2].

The same is for 19, whose index is [1, 1] because no row is 1, and in that row, the column is also 1. That is why it returns [1, 1] and the same for 18, whose index is [1, 2].

Applying condition to np argwhere() function

Pass the logical condition to the np argwhere() function to get the indices of specified elements that fulfill the condition.

Let’s say we only want the indices of elements greater than 4.

See the following code.

# app.py

import numpy as np

data = np.arange(8).reshape(2, 4)
print(data)
nonZeroIndices = np.argwhere(data > 4)
print('The indices of the elements that are > 4')
print(nonZeroIndices)

Output

python3 app.py
[[0 1 2 3]
 [4 5 6 7]]
The indices of the elements that are > 4
[[1 1]
 [1 2]
 [1 3]]

We have used the np arange() function in the above code to create a (2, 4) array.

We are printing only indices of elements that are greater than 4.

From the data array, you can see that 0 rows have no elements with a value greater than 4. So in the output, there are no 0 rows.

Let’s see another condition, and based on that, and we will get the indices.

# app.py

import numpy as np

data = np.arange(8).reshape(2, 4)
print(data)
nonZeroIndices = np.argwhere(data != 3)
print('The indices of the elements that are > 4')
print(nonZeroIndices)

Output

python3 app.py
[[0 1 2 3]
 [4 5 6 7]]
The indices of the elements that are > 4
[[0 0]
 [0 1]
 [0 2]
 [1 0]
 [1 1]
 [1 2]
 [1 3]]

In the above example, we only get indices whose element value is not 3. Otherwise, every index will be printed, even with 0 valued elements. That’s it for np.argwhere() function.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.