Home > Software engineering >  Reverse sort a column-based numpy array
Reverse sort a column-based numpy array

Time:01-27

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?

CodePudding user response:

Here you need Axis should be 0

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

CodePudding user response:

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
  •  Tags:  
  • Related