浅谈numpy数组的几种排序方式

  • Post category:Python

在Numpy中,我们可以使用不同的方法对数组进行排序。下面是几种常见的排序方式:

方法一:使用numpy.sort

numpy.sort()可以对数组进行排序。默认情况下,numpy.sort()函数会按升序对数组进行排序。下面是一个示例:

import numpy as np

arr = np.array([3, 1, 4, 2, 5])
sorted_arr = np.sort(arr)
print(sorted_arr)

输出结果为:

[1 2 3 4 5]

在上面的示例中,我们首先创建了一个包含5个整数的numpy数组。然后我们使用numpy.sort()函数对数组进行排序。最后,我们打印出排序后的数组。

方法二:使用numpy.argsort

numpy.argsort()函数返回一个数组,该数组包含原始数组中元素的索引,这些元素按升序排列。下面是一个示例:

import numpy as np

arr = np.array([3,1, 4, 2, 5])
sorted_indices = np.argsort(arr)
print(sorted_indices)

输出结果为:

[1 3 0 2 4]

在上面的示例中,我们首先创建了一个包含5个整的numpy数组。然后我们使用numpy.argsort()函数获取原始数组中元素的索引,这些元素按升序排列。最后,我们打印出排序后的索引数组。

方法三:使用numpy.lexsort

numpy.lexsort()可以对多个序列进行排序。下面是一个示例:

import numpy as np

a = np.array([3, 1, 4, 2, 5])
b = np.array([50, 30, 40, 20, 10])
sorted_indices = np.lexsort((b, a))
print(sorted_indices)

输出结果为:

[1 3 0 2 4]

在上面的示例中,我们首先创建了两个包含5个整数的numpy数组。然后我们使用numpy.lexsort()函数对这两个数组进行排序。最后,我们打印出排序后的索引数组。

希望这些示能够帮助您了解Numpy数组的几种排序方式。