Sort array's rows by another array in Python

PythonNumpySorting

Python Problem Overview


I'm trying to sort the rows of one array by the values of another. For example:

import numpy as np
arr1 = np.random.normal(1, 1, 80)
arr2 = np.random.normal(1,1, (80,100))

I want to sort arr1 in descending order, and to have the current relationship between arr1 and arr2 to be maintained (ie, after sorting both, the rows of arr1[0] and arr2[0, :] are the same).

Python Solutions


Solution 1 - Python

Use argsort as follows:

arr1inds = arr1.argsort()
sorted_arr1 = arr1[arr1inds[::-1]]
sorted_arr2 = arr2[arr1inds[::-1]]

This example sorts in descending order.

Solution 2 - Python

Use the zip function: zip( *sorted( zip(arr1, arr2) ) ) This will do what you need.

Now the explanation: zip(arr1, arr2) will combine the two lists, so you've got [(0, [...list 0...]), (1, [...list 1...]), ...] Next we run sorted(...), which by default sorts based on the first field in the tuple. Then we run zip(...) again, which takes the tuples from sorted, and creates two lists, from the first element in the tuple (from arr1) and the second element (from arr2).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmikeView Question on Stackoverflow
Solution 1 - PythonkeflavichView Answer on Stackoverflow
Solution 2 - PythonmklauberView Answer on Stackoverflow