Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting indices in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]]])

>Solution :

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]])]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading