How to sort 2D array column by ascending and row by descending in Python 3

Viewed 151

This is my array:

import numpy as np
boo = np.array([
    [10, 55, 12],
    [0, 81, 33],
    [92, 11, 3]
])

If I print:

[[10 55 12]
 [ 0 81 33]
 [92 11  3]]

How to sort array column by ascending and row by descending like this:

[[33 81 92]
 [10 12 55]
  [0 3  11]]
1 Answers
# import the necessary packages.
import numpy as np

# create the array.
boo = np.array([
    [10, 55, 12],
    [0, 81, 33],
    [92, 11, 3]
])

# we use numpy's 'sort' method to conduct the sorting process.
# we first sort the array along the rows.
boo = np.sort(boo, axis=0)

# we print to observe results.
print(boo)

# we therafter sort the resultant array again, this time on the axis of 1/columns.
boo = np.sort(boo, axis=1)

# we thereafter reverse the contents of the array.
print(boo[::-1])

# output shows as follows:
array([[33, 81, 92],
       [10, 12, 55],
       [ 0,  3, 11]])
Related