Let’s learn to sort indexes based on values in the Numpy Python library. We will use the Numpy argsort function.
We have a list of values:
[5, 7, 1, 3, 2]
I’d like to know the indexes of values sorted in ascending order.
My values are indexed by:
Value 5 – Index 0
Value 7 – Index 1
Value 1 – Index 2
Value 3 – Index 3
Value 2 – Index 4
Value 8 – Index 5
My values in ascending order: 1, 2, 3, 5, 7, 8
Indexes of these values: 2, 4, 3, 0, 1, 5
Argsort method
To sort indexes like that in Numpy, you need to use an argsort function like that.
import numpy as np my_list = np.array([5, 7, 1, 3, 2]) print(f"This is my array: \n {my_list}") indexes_sorted = my_list.argsort() print(f"There are indexes where you can find my values" f" in ascending order: \n {indexes_sorted}")
Indexes of sorted values have been returned.
Sorting multidimensional arrays
You can also sort indexes of multidimensional arrays. I’d reshape my array and show you how to sort the indexes of a 2D array.
import numpy as np my_list = np.array([5, 7, 1, 3, 2, 8]).reshape(3, 2) print(f"This is my array: \n {my_list}") indexes_sorted = my_list.argsort() print(f"There are indexes where you can find my values" f" in ascending order: \n {indexes_sorted}")
As you may notice, my 2D array has been sorted and the indexes have been returned.
Sorting different axis
You can also sort indexes based on different axes. By default, the argsort Numpy function sorts based on the -1 axis. Let’s see argsort sorting on axis = 0 and see how the sorted indexes change.
import numpy as np my_list = np.array([5, 7, 1, 3, 2, 8]).reshape(3, 2) print(f"This is my 2d array: \n {my_list}") indexes_sorted = my_list.argsort(axis=0) print(f"There are indexes where you can find my values" f" in ascending order on 0 axis: \n {indexes_sorted}")
As you can see, I used the axis=0 parameter in the argsort function.
Indexes have been sorted based on the 0 axis, which changed the results completely.