0

Given a numpy ndarray A, return its rank array.

Input : [[ 9 4 15 0 18] [16 19 8 10 1]]

Return value: [[4 2 6 0 8] [7 9 3 5 1]]

**but I didnt solve actually I solve but my solution is wrong

how can I solve ? please help meemphasized text**

import numpy as np
array=np.array([[9,4,15,0,18],[16,19,8,10,1]])


array_1=np.array([9,4,15,0,18])
array_2=np.array([16,19,8,10,1])

temp1 = array_1.argsort()
temp2 = array_2.argsort()

ranks1 = np.arange(len(array_1))[temp1.argsort()]
rankss=ranks1.argsort()
ranks2 = np.arange(len(array_2))[temp2.argsort()]



print(ranks1*array.ndim)
print(rankss)
adir abargil
  • 5,495
  • 3
  • 19
  • 29
  • why are you repeating argsort without any meanning? the result of `np.arange(len(array_1))[temp1.argsort()]` is equal to `temp1.argsort()` – adir abargil Jan 03 '21 at 15:01
  • repeat question check this link out [link](https://stackoverflow.com/questions/65505049/how-to-construct-a-rank-array-with-numpy-what-is-a-rank-array/65505159#65505159) – XXDIL Jan 03 '21 at 15:02
  • 1
    `array.flatten().argsort().argsort().reshape(array.shape)` – Stef Jan 03 '21 at 15:09
  • @adirabargil you are right ı make mistake while I write normally it wil not repeat – coder36 Jan 03 '21 at 15:16
  • @Stef solution is way more easier to implement, and faster for big data... – adir abargil Jan 03 '21 at 15:57

1 Answers1

1

If you pass axis=None to argsort then the source array is flattened at the first step (and only then arg-sorted).

So probably the shortest code is:

result = arr.argsort(axis=None).reshape(arr.shape)

No need to explicitely flatten the source array and only a single call to argsort.

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41