Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 row of arr1[0] and arr2[0, :] are the same).

share|improve this question

2 Answers

up vote 4 down vote accepted

Use argsort:

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

EDIT: changed to descending order

share|improve this answer
Thanks for the tip! – mike Jan 25 '12 at 18:50

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.