Home > Software engineering >  Getting the same order in ragged arrays in Python
Getting the same order in ragged arrays in Python

Time:07-03

I have two ragged arrays Ii0 and Iv0. I sort the values according to increasing j which Ii01 shows but then I want Iv01 to reflect the same sorting order. In general, I want the code to be able to handle many different shapes of Ii0 and Iv0. The current and desired outputs are attached.

import numpy as np

Ii0=np.array([[[0, 1],
        [0, 3],
        [1, 2]],
                 [[0, 3],
                  [2,5],
                  [0, 1]]])  

Iv0 = np.array([[[10],
                 [20],
                 [30]],
                        [[100],
                         [200],
                         [300]]])

Ii01 = np.array([sorted(i, key = lambda x : x[1]) for i in Ii0])
print("Ii01  =",Ii01)
Iv01 = np.array([sorted(i, key = lambda x : x[0]) for i in Iv0])
print("Iv01  =",Iv01)

The current output is

Ii01  = [array([[[0, 1],
        [1, 2],
        [0, 3]],

       [[0, 1],
        [0, 3],
        [2, 5]]])]
Iv01  = [array([[[ 10],
        [ 20],
        [ 30]],

       [[100],
        [200],
        [300]]])]

The expected output is

Ii01  = [array([[[0, 1],
        [1, 2],
        [0, 3]],

       [[0, 1],
        [0, 3],
        [2, 5]]])]
Iv01  = [array([[[ 10],
        [ 30],
        [ 20]],

       [[300],
        [100],
        [200]]])]

CodePudding user response:

import numpy as np

Ii0 = np.array([[
    [0, 1],
    [0, 3],
    [1, 2]],
    [[0, 3],
     [2, 5],
     [0, 1]]])

Iv0 = np.array([[[10],
                 [20],
                 [30]],
                [[100],
                 [200],
                 [300]]])

Ii01 = np.array([Ii[np.argsort(Ii[:, 1])] for Ii in Ii0])
print("Ii01  =", Ii01)
Iv01 = np.array([Iv[np.argsort(Ii[:, 1])] for Ii,Iv in zip(Ii0,Iv0)])
print("Iv01  =", Iv01)

we need to sort our first array with np.argsort which basically return index of sorted array and that indices we used to arrange second array (actually second array is not sorted, it rearranges passions based on first array sort)

  • Related