5
import numpy as np

a = np.array([[5,9,44],
              [5,12,43],
              [5,33,11]])

b = np.sort(a,axis=0)

print(b) #not well

# [[ 5  9 11]
# [ 5 12 43]
# [ 5 33 44]]

#desired output:

#[[5,33,11],
# [5,12,43],
# [5,9,44]]

what numpy sort does it changes rows completely(ofcourse based on lower to highest), but i would like to keep rows untouched. I would like to sort rows based on last column value, yet rows and values in array must stay untouched. Is there any pythonic way to do this? Thanks

filtertips
  • 801
  • 3
  • 12
  • 25

2 Answers2

11
ind=np.argsort(a[:,-1])
b=a[ind]

EDIT When you use axis in the sort, it sorts every column individually, what you want is to get indices of the sorted rows from the selected column (-1 is equivalent to the last column), and then reorder your original array.

anishtain4
  • 2,342
  • 2
  • 17
  • 21
2
a[a[:,-1].argsort()] 

may work for you

t..
  • 1,101
  • 1
  • 9
  • 22
  • For accessing the last column, it's more robust to use `-1` as opposed to accessing from the front of a list, since the former scales to different shapes. – user3483203 Jun 15 '18 at 16:31