I am trying to sort a numpy array using the argsort function.
Unfortunately this is not working and I can\'t see why :(
The code is:
import n
distance.argsort() returns an array of indices. The ith index does not tell you the rank of the ith element in distance. Rather, the ith index tells you that the ith element in the sorted array is distance[i].
In other words,
idx = distance.argsort()
assert (distance[idx] == np.sort(distance)).all()
Consider this small example from the docs:
In [236]: x = np.array([3, 1, 2])
In [237]: np.argsort(x)
Out[237]: array([1, 2, 0])
In [238]: x[np.argsort(x)]
Out[238]: array([1, 2, 3])
In [239]: x[1], x[2], x[0]
Out[239]: (1, 2, 3)
Calling argsort twice does gives you the rank of the ith element in distance:
In [240]: np.argsort(np.argsort(x))
Out[240]: array([2, 0, 1])
Understanding how this works is a good test of your understanding of argsort. However, calling argsort twice to find the rank is inefficient. Especially for larger arrays there are other, faster, ways to find the rank.
The following works for me:
distance.sort()
which returns
array([ 25.54, 27.49, 27.77, 28.36, 29. , 29.6 , 29.77, 30.26,
30.29, 30.77, 31.4 , 32.04, 32.04, 32.26, 32.33, 32.33,
32.65, 32.72, 33.01, 33.62, 33.62, 34. , 34.12, 34.33,
34.6 , 34.6 , 35.24, 35.54, 35.89, 36.01, 36.01, 36.5 ,
36.56, 36.56, 36.9 , 36.97, 37.01, 37.25, 37.25, 37.57,
37.61, 37.96, 38.16, 38.26, 38.26, 38.6 , 38.65, 38.74,
39.2 , 39.25, 39.29, 39.7 , 39.77, 40.33, 40.33, 40.36,
40.36, 40.4 , 40.45, 40.45, 40.45, 40.72, 40.72, 40.84,
40.84, 40.9 , 40.93, 40.93, 40.93, 40.93, 41.48, 41.49,
41.78, 42.5 , 42.85, 43.28, 43.29, 43.81, 43.81, 43.85,
43.97, 44.37, 44.37, 44.41, 44.98, 45. , 45.05, 45.05,
45.05, 45.62, 45.94, 45.94, 46.21, 46.21, 46.28, 46.85,
46.93, 46.98, 47.53, 47.56, 47.89, 48.1 , 48.25, 48.8 ,
48.8 , 49.37, 49.64, 50. , 50.09, 50.57, 50.58, 50.58,
51.14, 51.2 , 51.2 , 51.25, 51.25, 51.25, 51.25, 51.85,
51.97, 52.49, 52.56, 53.89, 53.89, 54.08, 54.5 , 54.5 ,
54.5 , 55.24, 55.78, 55.78, 56.48, 57.22, 57.22, 57.22,
57.85, 59.24, 59.41, 60.84, 61.7 , 62.08, 62.6 , 64.8 ,
66.05, 66.76, 67.13, 68.29, 73.73, 76.85])