Sort array's rows by another array in Python


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

Asked By: mike



Use argsort as follows:

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

This example sorts in descending order.

Answered By: keflavich

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

Answered By: mklauber
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.