NumPy argwhere()

The NumPy argwhere() method finds indices of array elements that are not zero as a 2D array.

Example

import numpy as np

originalArray = np.array([1, 0, 0, 4, -5])

# return the indices of elements that are not zero as a 2D array result = np.argwhere(originalArray )
print(result) ''' Output: [[0] [3] [4]] '''

argwhere() Syntax

The syntax of argwhere() is:

numpy.argwhere(array)

argwhere() Argument

The argwhere() method takes one argument:

  • array - an array whose non-zero indices are to be found

argwhere() Return Value

The argwhere() method returns indices of elements that are non-zero as a 2D array.


Example 1: numpy.argwhere() With Arrays

import numpy as np

numberArray = np.array([1, 0, 0, 4, -5])
stringArray = np.array(['Apple', 'Ball', '', 'Dog'])

# return indices of non-zero elements in numberArray as a 2D array numberResult = np.argwhere(numberArray) # return indices of non-empty elements in stringArray as a 2D array stringResult = np.argwhere(stringArray)
print('Array of non-empty indices in numberArray:\n', numberResult) print('\nArray of non-empty indices in stringArray:\n', stringResult)

Output

Array of non-empty indices in numberArray:
[[0]
 [3]
 [4]]

Array of non-empty indices in  stringArray:
 [[0]
 [1]
 [3]]

Example 2: numpy.argwhere() With 2-D Arrays

import numpy as np

array = np.array([[1, 0, 3],
                              [2, 0, 0],
                              [0, 4, 5]])

# return indices of elements that are not zero result = np.argwhere(array)
print(result)

Output

[[0 0]
 [0 2]
 [1 0]
 [2 1]
 [2 2]] 

Here, the output represents the positions of non-zero elements in the row-column format.

The first non-zero element is 1, which is in index [0, 0] in row-column format. Similarly, the second non-zero element is 3, which is in index [0, 2] in row-column format, and so on.


Example 3: numpy.argwhere() With Condition

We can also use argwhere() to find the indices of elements that satisfy the given condition.

import numpy as np

array = np.array([1, 2, 3, 4, 5, 6])

# check array elements for odd/even condition # return true if the array element is even result = np.argwhere(array%2==0)
print(result)

Output


[[1]
 [3]
 [5]]

Note: To group the indices by the dimension, rather than element, we use nonzero().

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community