ael
ael

Reputation: 5

Replace numpy array with order of each value

Hello I'm trying to do the following.

I have a matrix

a = np.array([[1,4,3], [0,3,7]])

I would like to transform the matrix so each cell new_a[i,j] contains the order (descending order) of the a[i,j] along the axis=1 So the result would be

a_new = np.array([[2,0,1], [2,1,0]])

I tried this (it works)

argsorts = np.argsort(a, axis=1) 

for i in a.shape[0]:
    a[i, argsorts[i]] = range(a.shape[1])[::-1]

I would like to change the for loop by something else Thank you

Upvotes: 0

Views: 155

Answers (1)

imdevskp
imdevskp

Reputation: 2223

Try

>>> 2-a.argsort()
[[2 0 1]
 [2 1 0]]

Upvotes: 0

Related Questions