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.
JavaScript
x
12
12
1
import numpy as np
2
Ii0 = [np.array([[0, 1],[0, 2],[1, 3],[2, 4],[4,3]]),
3
np.array([[0, 1],[0, 2],[1, 3],[2, 5],[4,3],[3,4]])]
4
5
Iv0 = [np.array([[10],[20],[30],[40],[50]]),
6
np.array([[25],[38],[41],[97],[65],[54]])]
7
8
Ii01 = [i[i[:,1].argsort()] for i in Ii0]
9
10
Iv01 = [i[i[:,0].argsort()] for i in Iv0]
11
print("Iv01 =",Iv01)
12
The current output is
JavaScript
1
11
11
1
Iv01 = [array([[10],
2
[20],
3
[30],
4
[40],
5
[50]]), array([[25],
6
[38],
7
[41],
8
[54],
9
[65],
10
[97]])]
11
The expected output is
JavaScript
1
11
11
1
Iv01 = [array([[10],
2
[20],
3
[30],
4
[50],
5
[40]]),array([[25],
6
[38],
7
[41],
8
[65],
9
[54],
10
[97]])]
11
Advertisement
Answer
Use:
JavaScript
1
3
1
Iv01 = [y[x[:,1].argsort()] for x, y in zip(Ii0, Iv0)]
2
print("Iv01 =",Iv01)
3
Output
JavaScript
1
11
11
1
Iv01 = [array([[10],
2
[20],
3
[30],
4
[50],
5
[40]]), array([[25],
6
[38],
7
[41],
8
[65],
9
[54],
10
[97]])]
11
Or as an alternative, use np.take_along_axis
:
JavaScript
1
2
1
Iv01 = [np.take_along_axis(y, x[:, 1].argsort().reshape((-1, 1)), 0) for x, y in zip(Ii0, Iv0)]
2