Search code examples
arrayspython-3.xnumpyminimum

Determine indices of N number of non-zero minimum values in array


I have an array of x size and need to determine the indices of n of the smallest values. I found this link (I have need the N minimum (index) values in a numpy array) discussing how to get multiple minimum values but it doesn't work as well when my array has zeros in it.

For example:

x = [10, 12, 11, 9, 0, 1, 15, 4, 10]
n = 3

I need to find the indices of the 3 lowest non-zero values so the result would be

non_zero_min_ind = [5, 7, 3]

They don't need to be be in any order. I am trying to do this in python 3. Any help would be greatly appreciated.


Solution

  • Using numpy:

    import numpy as np
    y = np.argsort(x)
    y[np.array(x)[y]!=0][:n]
    
    array([5, 7, 3])