Skip to content
Advertisement

Reordering a list based on another list in Python

I have two lists Ii0 and Iv0 containing numpy arrays. I am using argsort() to reorder elements in Ii0 to generate a new list Ii01. I want to use the same order to reorder elements in Iv0 to generate a new list Iv01. I present the current and expected output.

import numpy as np
Ii0 = [np.array([[0, 1],[0, 2],[1, 3],[2, 4],[4,3]]),
       np.array([[0, 1],[0, 2],[1, 3],[2, 5],[4,3],[3,4]])]

Iv0 = [np.array([[10],[20],[30],[40],[50]]),
        np.array([[25],[38],[41],[97],[65],[54]])]

Ii01 = [i[i[:,1].argsort()] for i in Ii0]

Iv01 = [i[i[:,0].argsort()] for i in Iv0]
print("Iv01 =",Iv01)

The current output is

Iv01 = [array([[10],
       [20],
       [30],
       [40],
       [50]]), array([[25],
       [38],
       [41],
       [54],
       [65],
       [97]])]

The expected output is

Iv01 = [array([[10],
               [20],
               [30],
               [50],
               [40]]),array([[25],
               [38],
               [41],
               [65],
               [54],
               [97]])]

Advertisement

Answer

Use:

Iv01 = [y[x[:,1].argsort()] for x, y in zip(Ii0, Iv0)]
print("Iv01 =",Iv01)

Output

Iv01 = [array([[10],
       [20],
       [30],
       [50],
       [40]]), array([[25],
       [38],
       [41],
       [65],
       [54],
       [97]])]

Or as an alternative, use np.take_along_axis:

Iv01 = [np.take_along_axis(y, x[:, 1].argsort().reshape((-1, 1)), 0) for x, y in zip(Ii0, Iv0)]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement