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
?
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.
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.
NumPy's np. argsort is able to do stable sorting through passing kind = 'stable' argument.
sort() returns the sorted array whereas np. argsort() returns an array of the corresponding indices.
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])
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With