首页 > 解决方案 > 如何在Python 3中按升序对二维数组列进行降序排序

问题描述

这是我的数组:

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

如果我打印:

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

如何按升序对数组列进行排序,按降序对行进行排序,如下所示:

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

标签: pythonpython-3.xnumpy

解决方案


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

推荐阅读