0

I want to sort (descending) a numpy array where the array is reshaped to one column structure. However, the following code seems not be working.

a = array([5,1,2,4,9,2]).reshape(-1, 1)
a_sorted = np.sort(a)[::-1]
print("a=",a)
print("a_sorted=",a_sorted)

Output is

a= [[5]
 [1]
 [2]
 [4]
 [9]
 [2]]
a_sorted= [[2]
 [9]
 [4]
 [2]
 [1]
 [5]]

That is due to the reshape function. If I remove that, the sort works fine. How can I fix that?

1
  • 4
    np.sort(a, axis=0)[::-1] should do it Commented Jan 27, 2022 at 11:09

2 Answers 2

1

Here you need Axis should be 0 (Column wise sorting)

np.sort(a,axis=0)[::-1]

Discussion:

a = np.array([[4,1],[23,2]])
print(a)
Output:
[[ 4  1]
 [23  2]]


# Axis None (Sort as a flatten array)
print(np.sort(a,axis=None))
Output:
[ 1  2  4 23]


# Axis None (Sort as a row wise **(By default is set to 1)**)
print(np.sort(a,axis=1))
[[ 1  4]
 [ 2 23]]

# Axis None (Sort as a column wise)
print(np.sort(a,axis=0))
[[ 4  1]
 [23  2]]

For more details have a look in: https://numpy.org/doc/stable/reference/generated/numpy.sort.html

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

2 Comments

This is the same as the comment on the question. At least make a reference.
I have added necessary info & reference. Thanks for you suggestion.
0

As @tmdavison pointed out in the comments you forgot to use the axis option since by default np sorts matrices by row. By calling the reshape function, in fact, you're transforming the array into a 1-column matrix which sorting by row is trivially the matrix itself. This would do the job

import numpy as np
a = np.array([5,1,2,4,9,2]).reshape(-1, 1)
a_sorted = np.sort(a, axis = 0)[::-1]
print("a=",a)
print("a_sorted=",a_sorted)

Extra points:

  • reference to the doc of sort
  • Next time remember to make the code reproducible (no np before array and no imports in your example). This was an easy case but it's not always like this

Comments

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.