Numpy argsort - what is it doing?
According to the documentation
Returns the indices that would sort an array.
2
is the index of0.0
.3
is the index of0.1
.1
is the index of1.41
.0
is the index of1.48
.
Example in np.argsort document
From the docs, the first line states "Returns the indices that would sort an array." Hence if you want the positions of the sorted values we have:
x = np.array([3, 1, 2])
np.argsort(x)
>>>array([1, 2, 0])
here we want the index positions of 1, 2 and 3 in x. The psotion of 3 is 0, the psotion of 1 is 1, and the position of 2 is 2, hence array([1, 2, 0])
= sorted_array(1,2,3).Again from the notes, " argsort returns an array of indices of the same shape as a that index data along the given axis in sorted order."
A more intuitive way of looking at what that means is to use a for loop, where we loop over our returned argsort
values, and then index the initial array with these values:
x = np.array([3, 1, 2])
srt_positions = np.argsort(x)
for k in srt_positions:
print x[k]
>>> 1, 2, 3
NumPy - descending stable arg-sort of arrays of any dtype
I think this formula should work:
import numpy as np
a = np.array([1, 2, 2, 3, 3, 3])
s = len(a) - 1 - np.argsort(a[::-1], kind='stable')[::-1]
print(s)
# [3 4 5 1 2 0]
How make np.argsort place empty strings at the END of an array instead of at the beginning
One simple way of getting the order you want would be using np.roll
:
lst = [ "Carrot", "Star", "Beta", "Zoro" , ""]
arr = np.array(lst)
idx = np.roll(arr.argsort(),np.count_nonzero(arr))
arr[idx]
# array(['Beta', 'Carrot', 'Star', 'Zoro', ''], dtype='<U6')
Using NumPy argsort and take in 2D arrays
I don't think there is a way to use np.take
without going to flat indices. Since dimensions are likely to change, you are better off using np.ravel_multi_index
for that, doing something like this:
a = np.argsort(dist, axis=1)
a = np.ravel_multi_index((np.arange(dist.shape[0])[:, None], a), dims=dist.shape)
Alternatively, you can use fancy indexing without using take
:s2 = dist[np.arange(4)[:, None], a]
Related Topics
How to Create Module-Wide Variables in Python
Python [Errno 98] Address Already in Use
Finding the Values of the Arrow Keys in Python: Why Are They Triples
How to Tell Pycharm What Type a Parameter Is Expected to Be
Extract Int from String in Pandas
Python: Give Start and End of Week Data from a Given Date
How to Test a Function with Input Call
Create File But If Name Exists Add Number
Pandas Expand Rows from List Data Available in Column
Method Not Allowed Flask Error 405
Wrapping Long Y Labels in Matplotlib Tight Layout Using Setp
Pandas Dataframe Column to List
How to Get Two Random Records with Django
When Should an Attribute Be Private and Made a Read-Only Property
How to Ignore One Single Specific Line with Pylint
How to Upsert Pandas Dataframe to Microsoft SQL Server Table