1

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]]])
1
  • The array in your example is a ragged shape. It's not clear which array you are talking about that has a shape of (2,). An array of that shape would look like np.array([1, 2]) Commented Jun 29, 2022 at 17:27

1 Answer 1

1

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]])]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.