Sort array's rows by another array in Python Sort array's rows by another array in Python numpy numpy

Sort array's rows by another array in Python


Use argsort as follows:

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

This example sorts in descending order.


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