How to find index of minimum non zero element with numpy?

np.nonzero(theta) returns the index of the values that are non-zero. In your case, it returns,

[1,2,3]

Then, theta[np.nonzero(theta)] returns the values

[1,2,3]

When you do np.argmin(theta[np.nonzero(theta)]) on the previous output, it returns the index of the value 1 which is 0.

Hence, the correct approach would be:

i,j = np.where( theta==np.min(theta[np.nonzero(theta)])) where i,j are the indices of the minimum non zero element of the original numpy array

theta[i,j] or theta[i] gives the respective value at that index.


I think you @Emily were very close to the correct answer. You said:

np.argmin(theta[np.nonzero(theta)]) gives an index of zero, which clearly isn't right. I think this is because it creates a new array of non zero elements first.

The last sentence is correct => the first one is wrong since it is expected to give the index in the new array.

Let's now extract the correct index in the old (original) array:

nztheta_ind = np.nonzero(theta)
k = np.argmin(theta[nztheta_ind])
i = nztheta_ind[0][k]
j = nztheta_ind[1][k]

or:

[i[k] for i in nztheta_ind]

for arbitrary dimensionality of original array.


#!/usr/bin/env python

# Solution utilizing numpy masking of zero value in array

import numpy as np
import numpy.ma as ma
a = [0,1,2,3]
a = np.array(a)

print "your array: ",a

# the non-zero minimum value
minval = np.min(ma.masked_where(a==0, a)) 
print "non-zero minimum: ",minval

# the position/index of non-zero  minimum value in the array
minvalpos = np.argmin(ma.masked_where(a==0, a))  
print "index of non-zero minimum: ", minvalpos