I have two NumPy arrays with the shape (74395, 1) storing float values where arr1[0] correlates to arr2[0] and so on. I would like to sort them together in ascending order by the values stored in the second array.
As an example:
JavaScript
x
8
1
arr1: [[1]
2
[2]
3
[3]]
4
5
arr2: [[6]
6
[2]
7
[4]]
8
wanted result:
JavaScript
1
8
1
arr1: [[2]
2
[3]
3
[1]]
4
5
arr2: [[2]
6
[4]
7
[6]]
8
How could I do that in python?
Advertisement
Answer
Use numpy.argsort
with numpy.take_along_axis
:
JavaScript
1
5
1
ind = arr2.argsort(axis=0)
2
3
np.take_along_axis(arr1, ind, axis=0)
4
np.take_along_axis(arr2, ind, axis=0)
5
Output:
JavaScript
1
7
1
(array([[2],
2
[3],
3
[1]]),
4
array([[2],
5
[4],
6
[6]]))
7