Home > Back-end >  Sort a numpy array using multiple index and different order
Sort a numpy array using multiple index and different order

Time:09-17

I have an array of size 300x5 and I am trying to sort the array in such a way that column with index 4 is my primary index and in ascending order, index 1 is secondary index and in descending order, index 3 is tertiary index and in ascending order. I have tried this using following code,

idx = np.lexsort((arr[:,3],arr[:,1][::-1],arr[:,4]))
arr= arr[idx]

where arr --> array of size 300x5

On executing this the secondary index also gets sorted in ascending order instead of descending order. Can anyone help me with this

CodePudding user response:

I think this is your answer, please check and give me your comment.

idx = np.lexsort((arr[:,3],arr[:,1],arr[:,4]))
arr = arr[idx][::-1]

CodePudding user response:

I think you want -arr[:,1] and not arr[:,1][::-1] as the secondary index.

>>> import numpy as np
>>> arr = np.random.randint(0, 21, (300, 5))
>>> arr
array([[ 0, 19,  6, 19, 17],
       [16,  2, 14, 17,  0],
       [ 8, 17,  3, 17, 12],
       ...,
       [ 4, 18, 18,  3,  8],
       [10, 15,  4, 12,  4],
       [ 9, 16, 12,  0, 12]])
>>> idx = np.lexsort((arr[:,3],-arr[:,1],arr[:,4]))
>>> arr = arr[idx]
>>> arr
array([[11, 20, 11, 18,  0],
       [11, 16, 12,  2,  0],
       [ 9, 16,  4,  8,  0],
       ...,
       [20,  4,  5, 11, 20],
       [ 9,  4,  0, 19, 20],
       [ 9,  2,  4, 10, 20]])
  • Related