This question asks about sorting 1D arrays, two solutions are given, first one suggests using argsort
twice, second, more time-efficient, uses it only once. What if I wanted to rank 2D array rowwise like this?
Using argsort
twice is one possibility:
def rank(x, axis=-1):
return np.argsort(np.argsort(x, axis=axis), axis=axis)
For the data:
x = np.array([
[1, 2, 30],
[4, 5, 6],
[90, 8, 7],
[12, 15, 10]
])
it returns correct retults:
rank(x, axis=0)
## array([[0, 0, 3],
## [1, 1, 0],
## [3, 2, 1],
## [2, 3, 2]])
rank(x, axis=1)
## array([[0, 1, 2],
## [0, 1, 2],
## [2, 1, 0],
## [1, 2, 0]])
But is there more efficient approach?