简体   繁体   中英

Creating ranks for the elements in array

So here is the problem:

Create the ranks for the given numeric array a. Hint: You can use np.rank() method

# Input
#> [ 9  4 15  0 17 16 17  8  9  0]

# Output

#> [4 2 6 0 8 7 9 3 5 1]

And I found this solution

import numpy as np
np.random.seed(10)
a = np.random.randint(20, size=10)
print(a.argsort().argsort())

But I can't understand why does it work.

When random seed is defined as 10, random integer function returns original input array. argsort() function returns an array of indices arranged to sort original array in ascending order. So when argsort() is executed only once it returns following output.

print(a.argsort())
[3 9 1 7 0 8 2 5 4 6]

This list shows indices of elements to sort original array. When you choose elements as a.argsort() function shows, you will get sorted version of the original array as follows.

print(a[3], a[9], a[1], a[7], a[0], a[8], a[2], a[5], a[4], a[6])
0 0 4 8 9 9 15 16 17 17

When argsort() function is applied to secondary array [3 9 1 7 0 8 2 5 4 6] , it will show rank of each element.

For example in original array first element is 9. When you apply argsort() first time, it puts index of that element, which is 0, at a position where index is 4. Because it is the 5th smallest element in original array. When you apply argsort() again, final output will generated. This element becomes first element of final output because secondary array stores its index. And its value will be 4 because its index in secondary array was 4.

To sum up, values of secondary array show indexes of elements to sort original array. In the meantime, its order shows rank of each element in original array implicitly. When second argsort() is applied, this implicit information come up. It generates an array that shows rank of each element in original array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM