首页 > 编程笔记 > Python笔记

NumPy排序函数(3个)

NumPy 提供了几个用于排序的函数,可以对数组中的元素进行排序。以下是一些常用的 NumPy 排序函数:

1) sort() 函数用于按照指定轴对数组对象中的元素进行排序,其语法格式如下:
sort(a,axis,kind,order)

2) argsort() 函数用于按照指定轴对数组对象中的元素进行排序,并返回排序后元素所对应的索引,其语法格式如下:
argsort(a,axis,kind,order)

3) msort() 函数用于按照第 1 个轴对数组对象中的元素进行排序,其语法格式如下:
msort(a)
其中,参数 a 表示数组对象。

示例代码如下:
import numpy as np

# 一维数组对象
a = np.array([7, 3, 4, 6, 1, 12, 3])
print(np.sort(a))
print('=====================')
print(np.argsort(a))
print('=====================')
print(np.msort(a))
print('=====================')

# 二维数组对象
b = np.array([[14, 2, 32, 12],
              [15, 6, 11, 8],
              [92, 10, 7, 12],
              [13, 8, 4, 6]])
print(np.sort(b))
print('=====================')
print(np.sort(b, 1))
print('=====================')
print(np.argsort(b))
print('=====================')
print(np.argsort(b, 1))
print('=====================')
print(np.msort(b))
print('=====================')

# 三维数组对象
c = np.array([[[13, 21, 3, 42],
               [15, 62, 6, 1],
               [2, 21, 33, 7]],
              [[16, 18, 21, 31],
               [66, 51, 41, 13],
               [65, 23, 22, 51]],
              [[54, 22, 43, 14],
               [14, 12, 34, 21],
               [33, 34, 5, 12]]])
print(np.sort(c))
print('=====================')
print(np.sort(c, 1))
print('=====================')
print(np.argsort(c))
print('=====================')
print(np.argsort(c, 1))
print('=====================')
print(np.msort(c))
运行结果为:
# 一维数组对象 
[ 1  3  4  6  7 12] 
===================== 
[5 1 2 3 0 6 4] 
===================== 
[ 1  3  4  6  7 12] 
===================== 
 
# 二维数组对象 
[[ 2 12 14 32] 
[ 6  8 11 15] 
[ 4  6  7 92] 
[ 4  6  8 13]] 
===================== 
[[ 2 12 14 32] 
[ 6  8 11 15] 
[ 7  92 10  4] 
[ 4  6  8 13]] 
===================== 
[[[ 1  2  3  0] 
  [ 2  3  1  0] 
  [ 2  0  1  3]] 
 
[[ 1  2  3  0] 
  [ 3  2  1  0] 
  [ 3  2  1  0]] 
 
[[ 2  1  3  0] 
  [ 0  1  2  3] 
  [ 2  3  0  1]]] 
===================== 
[[[ 1  2  3  0] 
  [ 2  3  1  0] 
  [ 2  0  1  3]] 
 
[[ 1  2  3  0] 
  [ 3  2  1  0] 
  [ 3  2  1  0]] 
 
[[ 2  1  3  0] 
  [ 0  1  2  3] 
  [ 2  3  0  1]]] 
===================== 
[[ 2 12 14 32] 
[ 6  8 11 15] 
[ 4  6  7 92] 
[ 4  6  8 13]] 
===================== 
 
# 三维数组对象 
[[[ 3  4 13 42] 
  [ 1 15 62  6] 
  [ 2  7 21 33]] 
 
[[13 16 18 21] 
  [41 51 66 13] 
  [22 23 51 65]] 
 
[[ 5 12 14 22] 
  [12 14 21 34] 
  [ 5 12  3 33]]] 
===================== 
[[[ 2 21  3 42] 
  [ 1  6 15 62] 
  [ 2  3 33  7]] 
 
[[13 16 18 21] 
  [13 41 51 66] 
  [22 23 51 65]] 
 
[[ 5 12 14 22] 
  [12 14 21 34] 
  [ 3  5 12 33]]] 
===================== 
[[[[0 2 1 3] 
   [3 1 0 2] 
   [1 2 3 0]] 
 
  [[0 1 2 3] 
   [2 3 0 1] 
   [2 3 1 0]] 
 
  [[0 1 2 3] 
   [1 0 2 3] 
   [2 3 0 1]]] 
===================== 
[[[ 2 21  3 42] 
  [ 1  6 15 62] 
  [ 2  3 33  7]] 
 
[[13 16 18 21] 
  [13 41 51 66] 
  [22 23 51 65]] 
 
[[ 5 12 14 22] 
  [12 14 21 34] 
  [ 3  5 12 33]]] 

相关文章