Receive Numpy mass indices
-
Hello, everyone.
I have this Numpy mass:
array([16, 17, 1, 3, 8, 10, 2, 19, 14, 18, 15, 6, 11, 13, 5, 4, 9, 0, 7, 12])
I need to first get the indexes of each element together with the value, and then sort out the collected list of elements in such a way as to get something like that:
[19: 7, 18: 9, 17: 1, 16: 0, 15: 10 ...]
I mean, in the final list, I have to quantify by lowering the values from the first list, but I need to add the index on the base list for each element. And you need to do it the fastest way. I have an idea how to do it, but it's kind of hard to get out. Maybe numpy has a way faster?
-
If you want to stay within the framework
numpy
and use its speed, it is possible to:import numpy as np
arr = np.array([16, 17, 1, 3, 8, 10, 2, 19, 14, 18, 15, 6, 11, 13, 5, 4, 9, 0, 7, 12])
sorted_idx = arr.argsort()[::-1]
sorted_arr = arr[sorted_idx]
print(np.stack([sorted_arr, sorted_idx]))
Conclusion:
[[19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0]
[ 7 9 1 0 10 8 13 19 12 5 16 4 18 11 14 15 3 6 2 17]]
♪
numpy
There's a sorting of mass indexes. This is where I get this sorting first, turn it over so that at the beginning there's a maximum, and then it's easy to get numbers from the index array. Well, if necessary, merge the indices and values into one set. Indexing innumpy
It must be pretty fast.