
np.argshort()是numpy 库中的一个函数,用于返回排序后的数组元素的索引。**numpy argshort()**函数将原始数组作为参数并返回一个数组。这个数组由与排序后的数组元素的索引相对应的元素的索引组成。这个数组由将数组排序的索引组成。
语法
numpy.argsort(arr, axis=- 1, kind=None, order=None)
参数
np.argsort() 函数以一个必要参数作为参数,并有三个可选参数。
- arr:数组在这个参数中被传递。这个数组是返回数组时需要的参数。要给argsort函数的数组在这个参数中给出。
- axis: 轴。在这个参数中给出了应该进行排序的轴。这个轴在默认情况下保持为-1。我们也可以在轴上给出None。
- kind:这是argsort()函数要使用的排序算法的种类。默认情况下为None 。例如,我们可以使用quicksort,mergesort,heapsort, 或者stable。kind参数中传递的这种算法在argsort函数中用于返回数组。
- order。它被用作优先级顺序。我们可以将值设置为str或者str的列表作为顺序。
返回值
它返回一个数组。这个数组由 对数组进行排序 的索引组成 。
使用np.argsort()返回索引的Python程序将对数组进行排序。
# Importing numpy as np
import numpy as np
# Creating a numpy array called arr
arr = np.array([5, 3, 7, 8, 1, 9, 2])
print("The array is : ", arr)
# Printing the shape of the array using shape function
print("Shape of the array is : ", arr.shape)
res = np.argsort(arr)
print("Indices that would sort the array is: ", res)
输出
The array is : [5 3 7 8 1 9 2]
Shape of the array is : (7,)
Indices that would sort the array is: [4 6 1 0 2 3 5]
在这个程序中,我们导入numpy以使用numpy函数。然后,我们创建了一个numpy数组。我们打印了这个数组,然后使用shape函数打印了数组的形状。然后,我们把这个数组传给了np.argsort() 函数 。 argshort() 函数返回一个数组。该数组由索引组成,这些索引将对数组中的元素进行排序。
在这个程序中,argshort() 函数以升序对元素进行排序。与其说是对元素进行排序,不如说是对相应的指数进行排序。这些指数可以用来对元素进行排序。
我们可以看到索引列表中的第一个元素是4,而 数组中的第4个 元素是1,因此1是第一个元素。同样地,在下一个位置,指数是6,而第6个 位置 的元素 是2。
在np.argsort()函数中,以mergesort为种类,以0为轴,返回将对数组进行排序的索引的Python程序
# Importing numpy as np
import numpy as np
# Creating a numpy array called arr
arr = np.array([5, 3, 7, 8, 1, 9, 2])
print("The array is : ", arr)
# Printing the shape of the array using shape function
print(" Shape of the array is : ", arr.shape)
res = np.argsort(arr, kind='mergersort', axis=0)
print("Indices that would sort the array is: ", res)
print(" The sorted array is: ", arr[res])
输出
The array is : [5 3 7 8 1 9 2]
Shape of the array is : (7,)
Indices that would sort the array is: [4 6 1 0 2 3 5]
在这个程序中,我们把种类和轴的值传给了merge sort和0,然后这个函数在轴0上使用merge sort算法对数组进行排序。然后我们打印了排序后的数组,绕过索引数组作为数组的索引。
numpy argshort() 函数的教程就到此为止。