一、排序
参数axis=0,按列排列,axis=1,按行排列。
np.random.seed(20201031)
a=np.random.rand(3,3)*10
a=np.around(a,2)
print(a)
b=np.sort(a,axis=1)
print(b)
c=np.sort(a,axis=0)
print(c)
d=np.sort(a)
print(d)
[[6.87 1.3 5.09]
[3.39 1.71 7.47]
[9.22 5.48 4.55]]
[[1.3 5.09 6.87]
[1.71 3.39 7.47]
[4.55 5.48 9.22]]
[[3.39 1.3 4.55]
[6.87 1.71 5.09]
[9.22 5.48 7.47]]
[[1.3 5.09 6.87]
[1.71 3.39 7.47]
[4.55 5.48 9.22]]
不设置axis参数,则默认按行排序。
参数order
tp = np.dtype([('name', 'S10'), ('age', np.int)])
a = np.array([("dawang", 21), ("yiyi", 18)], dtype=tp)
b = np.sort(a, order='name')
print(b)
c = np.sort(a, order='age')
print(c)
[(b'dawang', 21) (b'yiyi', 18)]
[(b'yiyi', 18) (b'dawang', 21)]
用元素的索引位置替代排序后的实际结果
一维数组
np.random.seed(20201028)
x = np.random.randint(0, 10, 10)
print(x)
y = np.argsort(x)
print(y)
print(x[y])
z= np.argsort(-x)
print(z)
print(x[z])
[5 5 1 8 9 1 7 9 5 6]
[2 5 0 1 8 9 6 3 4 7]
[1 1 5 5 5 6 7 8 9 9]
[4 7 3 6 9 0 1 8 2 5]
[9 9 8 7 6 5 5 5 1 1]
二维数组
np.random.seed(20201028)
x = np.random.rand(3, 3) * 10
x = np.around(x, 2)
print(x)
y = np.argsort(x, axis=0) # axis=0,按列排序
print(y)
y = np.argsort(x, axis=1) # axis=1,按行排序
print(y)
z = np.array([np.take(x[i], np.argsort(x[i])) for i in range(3)])
print(z)
[[3.55 1.02 8.3 ]
[5.16 3.54 0.77]
[0.86 6.71 5.53]]
[[2 0 1]
[0 1 2]
[1 2 0]]
[[1 0 2]
[2 1 0]
[0 2 1]]
[[1.02 3.55 8.3 ]
[0.77 3.54 5.16]
[0.86 5.53 6.71]]