0

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?

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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]]))

8 Comments

Why bring a huge dependency like numpy into this…?
@deceze Given OP uses 2d arrays, I automatically assumed its numpy :P.
@Chris Correct - I am indeed using numpy arrays and won't get around it ^^. Two things - In order for the changes to take effect I had to overwrite the variables. so arr1 = np.take_along... etc. Secondly, my arr1 values are all 0 after the transformation
@FLOROID You mean sorted arr1 starts with many zeros or they are all zeros ((arr1 == 0).all() == True)?
It must've been some weird bug, because after re-running the application the data is correctly sorted now as far as I can tell with this much data haha
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.