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

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That was fast,thank you.
some further explanation would be great!
2
a[a[:,-1].argsort()] 

may work for you

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.