Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 213
mike Avatar asked Jan 25 '12 18:01

mike


People also ask

How do I sort an array of rows?

NumPy arrays can be sorted by a single column, row, or by multiple columns or rows using the argsort() function. The argsort function returns a list of indices that will sort the values in an array in ascending value.

How do you sort an array from lowest to highest in Python?

Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.


1 Answers

Use argsort as follows:

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

This example sorts in descending order.

like image 182
keflavich Avatar answered Oct 01 '22 10:10

keflavich