Home > Net >  Sorting indices in Python
Sorting indices in Python

Time:06-30

I have an array I1. I want to arrange the indices in order of increasing j. For example, in [0, 1], i=0,j=1. But I am getting an error. The expected output is attached.

import numpy as np

I1=np.array([[[0, 1],
        [0, 3],
        [1, 2],
        [1, 4],
        [2, 5],
        [3, 4],
        [3, 6],
        [4, 7],
        [5, 4],
        [6, 7]],
                [[0, 1],
                  [0, 3],
                  [1, 2],
                  [1, 4],
                  [2, 5],
                  [3, 4],
                  [3, 6],
                  [4, 7]]])  

order1 = I1[0,:, 1].argsort()
I10 =np.array([I1[0][order1]])
print("I10 =",[I10])

The error is

in <module>
order1 = I1[0,:, 1].argsort()

IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed

The expected output is

array([[[0, 1],
        [1, 2],
        [0, 3],
        [1, 4],
        [3, 4],
        [5, 4],
        [2, 5],
        [3, 6],
        [4, 7],
        [6, 7]],[[0, 1],
                [1, 2],
                [0, 3],
                [1, 4],
                [3, 4],
                [2, 5],
                [3, 6],
                [4, 7]]])

CodePudding user response:

You need to use the key parameter of sorted() Python built-in function:

import numpy as np

I1=np.array([[[0, 1],
        [0, 3],
        [1, 2],
        [1, 4],
        [2, 5],
        [3, 4],
        [3, 6],
        [4, 7],
        [5, 4],
        [6, 7]],
                [[0, 1],
                  [0, 3],
                  [1, 2],
                  [1, 4],
                  [2, 5],
                  [3, 4],
                  [3, 6],
                  [4, 7]]])  
I1 = np.array([sorted(i, key = lambda x : x[1]) for i in I1])
print(I1)

Output:

[list([[0, 1], [1, 2], [0, 3], [1, 4], [3, 4], [5, 4], [2, 5], [3, 6], [4, 7], [6, 7]])
 list([[0, 1], [1, 2], [0, 3], [1, 4], [3, 4], [2, 5], [3, 6], [4, 7]])]
  • Related