Can I sort two related arrays in parallel using python?

Question:

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:

arr1: [[1]
       [2]
       [3]]

arr2: [[6]
       [2]
       [4]]

wanted result:

arr1: [[2]
       [3]
       [1]]

arr2: [[2]
       [4]
       [6]]

How could I do that in python?

Asked By: FLOROID

||

Answers:

Use numpy.argsort with numpy.take_along_axis:

ind = arr2.argsort(axis=0)

np.take_along_axis(arr1, ind, axis=0)
np.take_along_axis(arr2, ind, axis=0)

Output:

(array([[2],
        [3],
        [1]]),
 array([[2],
        [4],
        [6]]))
Answered By: Chris

zip the two together, sort, zip again to transpose the result, and destructure:

>>> arr1 = [1, 2, 3]
>>> arr2 = [6, 2, 4]
>>> arr2, arr1 = zip(*sorted(zip(arr2, arr1)))
>>> arr1
(2, 3, 1)
>>> arr2
(2, 4, 6)
Answered By: Samwise
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.