# What is the Numpy argwhere() Method in Python

Numpy.argwhere() function finds the indices of non-zero elements in a given input array. The function returns a new array with the indices of non-zero elements in a multi-dimensional, sorted format (one index per row).

### Syntax

``numpy.argwhere(arr)``

### Parameters

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

### Example 1

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

``````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]. The same applies to the “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. So that is why it returns [1, 1] and the same for 18, whose index is [1, 2].

### Example 2

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.

``````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

``````[[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.

The data array shows that 0 rows have no elements with a value greater than 4. So in the output, there are no 0 rows.

### Example 3

``````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

``````[[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.

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