sort()
方法将数组按升序排序。
示例
import numpy as np
array = np.array([10, 2, 9, -1])
# sort an array in ascending order
array2 = np.sort(array)
print(array2)
# Output : [-1 2 9 10]
sort() 语法
sort()
的语法是
numpy.sort(array, axis, order, kind)
sort() 参数
sort()
方法接受四个参数
array
- 要排序的数组axis
(可选) - 追加值的轴order
(可选) - 要比较的字段kind
(可选) - 排序算法
注意事项
- 默认情况下,
axis
为 -1,数组将根据最后一个轴进行排序。 kind
可以是quicksort
(默认),mergesort
, 或heapsort
。
sort() 返回值
sort()
方法返回一个排序后的数组。
示例 1:对数字数组进行排序
import numpy as np
array = np.array([10.20, 2.10, 9.9, -1.4])
# sort the array in ascending order.
array2 = np.sort(array)
print(array2)
输出
[-1.4 2.1 9.9 10.2]
示例 2:对字符串数组进行排序
import numpy as np
array = np.array(['Apple', 'apple', 'Ball', 'Cat'])
# sort a string array based on their ASCII values.
array2 = np.sort(array)
print(array2)
输出
['Apple' 'Ball' 'Cat' 'apple']
示例 3:对多维数组进行排序
多维数组根据给定的轴进行排序。
import numpy as np
array = np.array([[3, 10, 2], [1, 5, 7], [2, 7, 5]])
# sort column wise based on the axis 1
array2 = np.sort(array)
# flattens the given array and sorts the flattened array
array3 = np.sort(array, axis = None)
# sort array row wise
array4 = np.sort(array, axis = 0)
print('Sorted based on last axis(1): \n', array2)
print('Sorted a flattened array', array3)
print('Sorted based on axis 0: \n', array4)
输出
Sorted based on last axis(1) : [[ 2 3 10] [ 1 5 7] [ 2 5 7]] Sorted a flattened array [ 1 2 2 3 5 5 7 7 10] Sorted based on axis 0 : [[ 1 5 2] [ 2 7 5] [ 3 10 7]]
当根据轴 **0** 进行排序时,会比较行。首先对第一列的元素进行排序,然后是第二列,依此类推。所有列都是独立排序的。
示例 4:使用 order 参数排序数组
import numpy as np
datatype = [('name', 'U7'), ('age', int), ('height', int)]
people = [
('Alice', 25, 170),
('Bob', 30, 180),
('Charlie', 35, 175)
]
array = np.array(people, dtype = datatype)
# sort the array based on height
array2 = np.sort(array, order = 'height')
print(array2)
输出
[('Alice', 25, 170) ('Charlie', 35, 175) ('Bob', 30, 180)]
示例 5:使用多个 order 参数排序数组
import numpy as np
datatype = [('name', 'U7'), ('age', int), ('height', int)]
people = [
('Alice', 25, 170),
('Bob', 30, 180),
('Charlie', 35, 175),
('Dan', 40, 175),
('Eeyore', 25, 180)
]
array = np.array(people, dtype = datatype)
# sort the people array on the basis of height
# if heights are equal, sort people on the basis of age
array2 = np.sort(array, order = ('height', 'age'))
print(array2)
输出
[('Alice', 25, 170) ('Charlie', 35, 175) ('Dan', 40, 175) ('Eeyore', 25, 180) ('Bob', 30, 180)]
kind 参数
kind
参数在 NumPy sort()
中用于指定用于排序的算法。例如,
import numpy as np
array = np.array([10, 2, 9, 1])
# sort an array in ascending order by quicksort algorithm
array2 = np.sort(array, kind = 'quicksort')
print(array2)
# Output : [1 2 9 10]
kind
参数可以取几个值,包括:
- quicksort (默认):这是一种快速算法,适用于大多数情况,即元素随机或均匀分布的中小型数组。
- mergesort:这是一种稳定的递归算法,适用于具有重复元素的大型数组。
- heapsort:这是一种较慢但保证 O(n log n) 的排序算法,适用于元素随机或均匀分布的小型数组。
kind
参数对输出没有直接影响,但它决定了方法的性能。