Efficiently sorting a numpy array in descending order? Efficiently sorting a numpy array in descending order? numpy numpy

Efficiently sorting a numpy array in descending order?


temp[::-1].sort() sorts the array in place, whereas np.sort(temp)[::-1] creates a new array.

In [25]: temp = np.random.randint(1,10, 10)In [26]: tempOut[26]: array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])In [27]: id(temp)Out[27]: 139962713524944In [28]: temp[::-1].sort()In [29]: tempOut[29]: array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])In [30]: id(temp)Out[30]: 139962713524944


>>> a=np.array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])>>> np.sort(a)array([2, 2, 4, 4, 4, 4, 5, 6, 7, 8])>>> -np.sort(-a)array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])


For short arrays I suggest using np.argsort() by finding the indices of the sorted negatived array, which is slightly faster than reversing the sorted array:

In [37]: temp = np.random.randint(1,10, 10)In [38]: %timeit np.sort(temp)[::-1]100000 loops, best of 3: 4.65 µs per loopIn [39]: %timeit temp[np.argsort(-temp)]100000 loops, best of 3: 3.91 µs per loop