Skip to content

Instantly share code, notes, and snippets.

@stevenvo
Last active March 16, 2021 08:23
Show Gist options
  • Select an option

  • Save stevenvo/e3dad127598842459b68 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

Thanks!

@malikasri94

Copy link
Copy Markdown

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
Copy Markdown

You could reverse the .argsort() results:

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

@dmitrymoshkin

Copy link
Copy Markdown

Cool, thanx

@ajoyvmw

ajoyvmw commented Jun 16, 2019

Copy link
Copy Markdown

Very nice!

@nalin-mathur-oyo

Copy link
Copy Markdown

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

dzy0023 commented Dec 3, 2019

Copy link
Copy Markdown

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

Lelik92 commented Nov 16, 2020

Copy link
Copy Markdown

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