Home > Software design >  Rank specific columns of 2D arrays inside a 3D Array
Rank specific columns of 2D arrays inside a 3D Array

Time:10-19

I have many 2D arrays inside of a 3D array.

Let’s assume that shape of the 3D array is (3, 5, 5). Therefore, I have 3 2D Arrays of shape (5, 5).

Column #4 (idx of 3) in each 2D array has a certain value as per below. I want to replace those values with corresponding ranks in descending order. The highest value will correspond to the maximum number of records (I.e. shape[1]) in 2D array, and the lowest value will have a rank of 1 (not 0).

I know that this could be achieved using NumPy’s argsort() function. But what I want to avoid is looping through the 3D array. Could you please suggest the most efficient, native NumPy and loop-free alternatives?

Thank you!

[[[1. 0. 0.10. 0.]
  [2. 0. 0. 9. 0.]
  [3. 0. 0. 8. 0.]
  [4. 0. 0. 7. 0.]
  [5. 0. 0. 6. 0.]]
 [[1. 0. 0. 199. 0.]
  [2. 0. 0. 198. 0.]
  [3. 0. 0. 196. 0.]
  [4. 0. 0. 190. 0.]
  [5. 0. 0. 160. 0.]]
 [[1. 0. 0. 999. 0.]
  [2. 0. 0. 870. 0.]
  [3. 0. 0. 270. 0.]
  [4. 0. 0. 100. 0.]
  [5. 0. 0. 80. 0.]]]


CodePudding user response:

I suggest:

arr[:, :, 3] = arr[:, :, 3].argsort(axis=1).argsort(axis=1)   1

Note that using argsort twice is necessary to obtain "ranks".

  • Related