简体   繁体   中英

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

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]]
# 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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM