np.argsort函数用法详解
函数解释
np.argsort是NumPy库中的一个函数,用于对数组进行排序并返回排序后的索引。它不会直接对数组进行排序,而是返回一个数组,这个数组中的元素是原数组中元素按升序排序后的索引。
numpy.argsort(a, axis=-1, kind=None, order=None)
参数如下:
代码示例
一维数组
import numpy as np
arr = np.array([3, 1, 2])
sorted_indices = np.argsort(arr)
print(sorted_indices)
[1 2 0]
二维数组
import numpy as np
arr = np.array([[3, 1, 2], [6, 4, 5]])
sorted_indices = np.argsort(arr, axis=1)
print(sorted_indices)
[[1 2 0]
[1 2 0]]
降序排序
import numpy as np
arr = np.array([3, 1, 2])
sorted_indices = np.argsort(arr)[::-1] ## 或者sorted_indices = np.argsort(-arr)
print(sorted_indices)
[0 2 1]
作者:chen_znn