1. 排序
numpy.sort()
numpy.sort(a[, axis=-1, kind='quicksort', order=None]) :返回排完序的数组的副本
axis:排序沿数组的(轴)方向,0表示按行,1表示按列,None表示展开来排序,默认为-1,表示沿最后的轴排序。
kind:排序的算法,提供了快排'quicksort'、混排'mergesort'、堆排'heapsort', 默认为‘quicksort'。
order:排序的字段名,可指定字段排序,默认为None。
如果从大到小倒序排序可以sort(-a),然后输出时再反向
【例】指定字段名排序
import numpy as np
dt = np.dtype([('name', 'S10'), ('age', np.int)])
a = np.array([("Mike", 21), ("Nancy", 25), ("Bob", 17), ("Jane", 27)], dtype=dt)
b = np.sort(a, order='name')
print(b)
# [(b'Bob', 17) (b'Jane', 27) (b'Mike', 21) (b'Nancy', 25)]
b = np.sort(a, order='age')
print(b)
# [(b'Bob', 17) (b'Mike', 21) (b'Nancy', 25) (b'Jane', 27)]
numpy.argsort()
numpy.argsort(a[, axis=-1, kind='quicksort', order=None]) :排序后,用元素的索引位置替代排序后的实际结果
【例】对数组沿给定轴执行间接排序,并使用指定排序类型返回数据的索引数组。这个索引数组用于构造排序后的数组。
import numpy as np
np.random.seed(20200612)
x = np.random.randint(0, 10, 10)
print(x)
# [6 1 8 5 5 4 1 2 9 1]
y = np.argsort(x)
print(y)
# [1 6 9 7 5 3 4 0 2 8]
print(x[y])
# [1 1 1 2 4 5 5 6 8 9]
y = np.argsort(-x) #得到倒序排序的索引
print(y)
# [8 2 0 3 4 5 7 1 6 9]
print(x[y]) #用倒序排序的索引直接输出即可
# [9 8 6 5 5 4 2 1 1 1]
【例】
import numpy as np
np.random.seed(20200612)
x = np.random.rand(5, 5) * 10
x = np.around(x, 2)
print(x)
# [[2.32 7.54 9.78 1.73 6.22]
# [6.93 5.17 9.28 9.76 8.25]
# [0.01 4.23 0.19 1.73 9.27]
# [7.99 4.97 0.88 7.32 4.29]
# [9.05 0.07 8.95 7.9 6.99]]
y = np.argsort(x)
print(y)
# [[3 0 4 1 2]
# [1 0 4 2 3]
# [0 2 3 1 4]
# [2 4 1 3 0]
# [1 4 3 2 0]]
y = np.argsort(x, axis=0)
print(y)
# [[2 4 2 0 3]
# [0 2 3 2 0]
# [1 3 4 3 4]
# [3 1 1 4 1]
# [4 0 0 1 2]]
y = np.argsort(x, axis=1)
print(y)
# [[3 0 4 1 2]
# [1 0 4 2 3]
# [0 2 3 1 4]
# [2 4 1 3 0]
# [1 4 3 2 0]]
y = np.array([np.take(x[i], np.argsort(x[i])) for i in range(5)])
#numpy.take(a, indices, axis=None, out=None, mode='raise')沿轴从数组中获取元素。
print(y)
# [[1.73 2.32 6.22 7.54 9.78]
# [5.17 6.93 8.25 9.28 9.76]
# [0.01 0.19 1.73 4.23 9.27]
# [0.88 4.29 4.97 7.32 7.99]
# [0.07 6.99 7.9 8.95 9.05]]
numpy.lexsort()
numpy.lexsort(keys[, axis=-1]) :使用键序列执行间接稳定排序
【例】按照第一列的升序或者降序对整体数据进行排序。
import numpy as np
np.random.seed(20200612)
x = np.random.rand(5, 5) * 10
x = np.around(x, 2)
print(x)
# [[2.32 7.54 9.78 1.73 6.22]
# [6.93 5.17 9.28 9.76 8.25]
# [0.01 4.23 0.19 1.73 9.27]
# [7.99 4.97 0.88 7.32 4.29]
# [9.05 0.07 8.95 7.9 6.99]]
index = np.lexsort([x[:, 0]])
print(index)
# [2 0 1 3 4]
y = x[index]
print(y)
# [[0.01 4.23 0.19 1.73 9.27]
# [2.32 7.54 9.78 1.73 6.22]
# [6.93 5.17 9.28 9.76 8.25]
# [7.99 4.97 0.88 7.32 4.29]
# [9.05 0.07 8.95 7.9 6.99]]
index = np.lexsort([-1 * x[:, 0]])
print(index)
# [4 3 1 0 2]
y = x[index]
print(y)
# [[9.05 0.07 8.95 7.9 6.99]
# [7.99 4.97 0.88 7.32 4.29]
# [6.93 5.17 9.28 9.76 8.25]
# [2.32 7.54 9.78 1.73 6.22]
# [0.01 4.23 0.19 1.73 9.27]]
【例】序列中的最后一个键用于主排序顺序,倒数第二个键用于辅助排序顺序,依此类推。
import numpy as np
x = np.array([1, 5, 1, 4, 3, 4, 4])
y = np.array([9, 4, 0, 4, 0, 2, 1])
a = np.lexsort([x])