Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort numpy matrix row values in ascending order

I have this following numpy matrix that I want to sort in ascending order based on the 3rd column values.

[[  3.05706500e+06   4.98000000e+01  -2.62500070e+01  -9.38135544e+01]
 [  3.05706600e+06   4.98000000e+01  -3.00000056e+01  -9.38135544e+01]
 [  3.05706700e+06   4.98000000e+01  -3.37500042e+01  -9.38135544e+01]
 [  3.05706800e+06   4.98000000e+01  -3.75000028e+01  -9.38135544e+01]]

This is the matrix I actually want.

[[  3.05706800e+06   4.98000000e+01  -3.75000028e+01  -9.38135544e+01]
 [  3.05706700e+06   4.98000000e+01  -3.37500042e+01  -9.38135544e+01]
 [  3.05706600e+06   4.98000000e+01  -3.00000056e+01  -9.38135544e+01]
 [  3.05706500e+06   4.98000000e+01  -2.62500070e+01  -9.38135544e+01]]

How do I do this using just numpy? Any help would be appreciated. Thanks!

like image 456
prrao Avatar asked Apr 09 '12 19:04

prrao


People also ask

How do I sort rows in NumPy?

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 a matrix descending order NumPy?

Use numpy. ndarray. sort() to sort a NumPy array in descending order. Use the syntax array[::-1] to reverse array .


1 Answers

Given your array

>>> arr
array([[  3.05706500e+06,   4.98000000e+01,  -2.62500070e+01,
         -9.38135544e+01],
       [  3.05706600e+06,   4.98000000e+01,  -3.00000056e+01,
         -9.38135544e+01],
       [  3.05706700e+06,   4.98000000e+01,  -3.37500042e+01,
         -9.38135544e+01],
       [  3.05706800e+06,   4.98000000e+01,  -3.75000028e+01,
         -9.38135544e+01]])

you can simply use numpy.sort with axis=0 to sort it as desired

>>> numpy.sort(arr,axis=0)
array([[  3.05706500e+06,   4.98000000e+01,  -3.75000028e+01,
         -9.38135544e+01],
       [  3.05706600e+06,   4.98000000e+01,  -3.37500042e+01,
         -9.38135544e+01],
       [  3.05706700e+06,   4.98000000e+01,  -3.00000056e+01,
         -9.38135544e+01],
       [  3.05706800e+06,   4.98000000e+01,  -2.62500070e+01,
         -9.38135544e+01]])
>>> 

I believe my previous answer was wrong as I misunderstood the question. Here is the correct answer

>>> arr[arr[:,2].argsort()]
array([[  3.05706800e+06,   4.98000000e+01,  -3.75000028e+01,
         -9.38135544e+01],
       [  3.05706700e+06,   4.98000000e+01,  -3.37500042e+01,
         -9.38135544e+01],
       [  3.05706600e+06,   4.98000000e+01,  -3.00000056e+01,
         -9.38135544e+01],
       [  3.05706500e+06,   4.98000000e+01,  -2.62500070e+01,
         -9.38135544e+01]])
>>> 
like image 146
Abhijit Avatar answered Oct 14 '22 17:10

Abhijit