Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

np.argsort which excludes zero values

I have an array [0.2,0,0,0,0.3,0,0,0,0.4]. I'm using np.argsort to sort values and get that indexes.

So, for my example, it will be something like [1,5,9,2,3,4,6...]. However, I would like to get array of indexes only for non zero values.

In my example only [1,5,9].

How do I implement it in python with pandas and numpy?

like image 538
user3318023 Avatar asked Nov 29 '16 03:11

user3318023


People also ask

What does Argsort () do in Python?

In Python, the NumPy library has a function called argsort() , which computes the indirect sorting of an array. It returns an array of indices along the given axis of the same shape as the input array, in sorted order.

What does NumPy Argsort return?

argsort. Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.

Is NP Argsort stable?

NumPy's np. argsort is able to do stable sorting through passing kind = 'stable' argument.

What is the difference between Argsort and sort?

sort() returns the sorted array whereas np. argsort() returns an array of the corresponding indices.


2 Answers

Using np.nonzero and indexing trick

def sparse_argsort(arr):
    indices = np.nonzero(arr)[0]
    return indices[np.argsort(arr[indices])]

sparse_argsort(a)

array([0, 4, 8])

one liner:

(lambda a: (lambda a_, i_: i_[np.argsort(a_[i_])])(a,np.nonzero(a)[0]))(a)

array([0, 4, 8])
like image 127
Kh40tiK Avatar answered Oct 05 '22 21:10

Kh40tiK


one line numpy

np.where(a != 0, a, np.nan).argsort()[:(a != 0).sum()]

same logic, two lines, more efficient

nz = a != 0
np.where(nz, a, np.nan).argsort()[:nz.sum()]

array([0, 4, 8])
like image 37
piRSquared Avatar answered Oct 05 '22 23:10

piRSquared