How to rank values in Numpy array?

Let’s check how to rank values in a Numpy array by axis.
Numpy rank values by axis

Sometimes values do not matter so much. You may want to know the order.

Ranking with argsort

See how to rank values using the argsort Numpy function.

import numpy as np

my_array = np.array([[1, 56, 55, 15],
                     [5, 4, 33, 53],
                     [3, 6, 7, 19]])

sorted_array = np.argsort(my_array, axis=0)

print(f"These are ranks of array values: \n {sorted_array}")

Numpy rank values by axis

As you can see, there are ranks given for the values in your array. You can work on them further.

See also  How to calculate mode in Python?

Ranking over another axis

Do you want to rank it differently? No problem. See:

import numpy as np

my_array = np.array([[1, 56, 55, 15],
                     [5, 4, 33, 53],
                     [3, 6, 7, 19]])

sorted_array = np.argsort(my_array, axis=1)

print(f"These are ranks of array values: \n {sorted_array}")

Numpy rank values by axis python

By changing the axis parameter to 1, the ranking is performed within each row rather than each column.

See also  How to Generate a 3D Meshgrid Array in Numpy