0
import numpy as np

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]
 [56 12  4]
 [ 1 21  3]]

If I wish to get the reverse sorting based on any column, say 3rd, what changes do i make to the code? Meaning, I wish to get:

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

P.s Yes I understand this is an easy question but I couldn't find an answer that I understood and was based for matrix and not an array or vector. TIA :)

user10089194
  • 339
  • 1
  • 5
  • 14
  • Addendum: By reverse I mean decreasing order. – user10089194 Oct 23 '18 at 15:49
  • So in your case, `mat[mat[:, 2].argsort()[::-1]` would work. – miradulo Oct 23 '18 at 15:52
  • or `mat[-mat[:,2].argsort()]`. – Divakar Oct 23 '18 at 15:53
  • @miradulo okay thanks. Both of them work. I have a question when using 'mat[mat[:, 2].argsort()[::-1]' what does the :: signify in [::-1]? why can't i write just [-1]? – user10089194 Oct 23 '18 at 16:38
  • @user10089194 No worries. The [Indexing](https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html) section of the NumPy docs has all the details about indexing in NumPy, but it is just extending the basic Python slice notation, which has the notation `[::]`. So with `[::-1]`, you're including all elements of the array and stepping backwards through it. – miradulo Oct 23 '18 at 16:45
  • Ahh thanks man. Understood clearly. – user10089194 Oct 23 '18 at 17:45

2 Answers2

1

Just reverse the argsort indices:

mat_sort = mat[mat[:, 2].argsort()[::-1]]
jpp
  • 159,742
  • 34
  • 281
  • 339
1
print(mat_sort[::-1]) #just print in reverse
mad_
  • 8,121
  • 2
  • 25
  • 40