4

I try to sort values in an array in descending order. If I try it in ascending order it works, but when i do it descending I get an error.

e = np.array([[5.,3.,8.],[6.,7.,1.],[4.,8.,2.]])
e.sort()

result:

e = array([[3.,5.,8.],[1.,6.,7.],[2.,4.,8.]])

now in reverse order:

  e.sort(reverse=True)

result:

TypeError: 'reverse' is an invalid keyword argument for this function

I also tried e.sort(key=itemgetter(1)) after from operator import itemgetter but the same error appears ('reverse' is replaced by 'key').

Why is this the case? Why does it not work? Why this error (this is the way to use key or reverse right)?

1
  • I've found my result here: link f = -np.sort(-e) worked perfect! Commented Aug 17, 2017 at 15:27

3 Answers 3

2

You couldn't use the key or reverse keyword arguments according to numpy documentation. You can sort the array in ascending order and then reverse it with the [::-1] slice or use the reversed() view.

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

Comments

0

Try using fliplr after sitting in ascending order https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.fliplr.html#numpy.fliplr

1 Comment

I've also some nan values in my dataset which should stay at the end of the array. By using fliplr these would be put in front. Otherwise this would be perfect.
0

Why is this the case? Why does it not work?

Simply because numpy's sort function doesn't supply that functionality.

One way to "fix" this problem is to argsort on the column of interest. You can then reverse the output and use that to index e to get the items sorted as you wish:

>>> import numpy as np
>>> e = np.array([[5.,3.,8.],[6.,7.,1.],[4.,8.,2.]])
>>> e
array([[ 5.,  3.,  8.],
       [ 6.,  7.,  1.],
       [ 4.,  8.,  2.]])
>>> col = 0
>>> idx_asc = np.argsort(e[:, col])
>>> idx_desc = idx_asc[::-1]
>>> e[idx_desc]
array([[ 6.,  7.,  1.],
       [ 5.,  3.,  8.],
       [ 4.,  8.,  2.]])

Note that this approach is less flexible (and less convenient) than being able to pass a key and reverse=True. Specifically, if you want to sort on multiple columns to break ties, this approach fails.

2 Comments

No column is of special interest, all rows should be sorted indivudually.
@SVerhoef -- I guess I don't understand what you're getting at with they key=itemgetter(1) then ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.