Skip to content

Instantly share code, notes, and snippets.

@stevenvo
Last active March 16, 2021 08:23
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevenvo/e3dad127598842459b68 to your computer and use it in GitHub Desktop.
Save stevenvo/e3dad127598842459b68 to your computer and use it in GitHub Desktop.
Sort array by nth column in Numpy
# sort array with regards to nth column
arr = arr[arr[:,n].argsort()]
@sywyyhykkk
Copy link

Thanks!

@malikasri94
Copy link

Could you tell me the code if I want the decreasing order?
For example:
mat = np.array([[1,21,3],[5,4,2],[56,12,4]])
mat_sort = mat[mat[:,2].argsort()]
print(mat_sort)

Output:
[[ 5 4 2]
[ 1 21 3]
[56 12 4]]

But if I want sorting based on 3rd column in decreasing order?

@philippemiron
Copy link

You could reverse the .argsort() results:

mat_sort = mat[mat[:,2].argsort()[::-1]]

@dmitrymoshkin
Copy link

Cool, thanx

@ajoyvmw
Copy link

ajoyvmw commented Jun 16, 2019

Very nice!

@nalin-mathur-oyo
Copy link

This is not working when I am trying it out. Posting a code snippet to show the results I am getting. Please suggest as to what I should do.

Currently using python 3.7.4.
Screenshot 2019-08-08 at 12 36 24 PM

@dzy0023
Copy link

dzy0023 commented Dec 3, 2019

This is not working when I am trying it out. Posting a code snippet to show the results I am getting. Please suggest as to what I should do.

Currently using python 3.7.4.
Screenshot 2019-08-08 at 12 36 24 PM

its a func for ndarray

@Lelik92
Copy link

Lelik92 commented Nov 16, 2020

Could I sort all matrix columns in descending order in similar way by using argsort()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment