📜  Python中的 numpy.argsort()

📅  最后修改于: 2022-05-13 01:55:48.931000             🧑  作者: Mango

Python中的 numpy.argsort()

numpy.argsort()函数用于使用 kind 关键字指定的算法沿给定轴执行间接排序。它返回一个与 arr 形状相同的索引数组,用于对数组进行排序。

代码#1:

# Python program explaining
# argpartition() function
   
import numpy as geek
  
# input array
in_arr = geek.array([ 2, 0,  1, 5, 4, 1, 9])
print ("Input unsorted array : ", in_arr) 
  
out_arr = geek.argsort(in_arr)
print ("Output sorted array indices : ", out_arr)
print("Output sorted array : ", in_arr[out_arr])
输出:
Input unsorted array :  [2 0 1 5 4 1 9]
Output sorted array indices :  [1 2 5 0 4 3 6]
Output sorted array :  [0 1 1 2 4 5 9]


代码#2:

# Python program explaining
# argpartition() function
  
import numpy as geek
  
# input 2d array
in_arr = geek.array([[ 2, 0, 1], [ 5, 4, 3]])
print ("Input array : ", in_arr) 
  
# output sorted array indices
out_arr1 = geek.argsort(in_arr, kind ='mergesort', axis = 0)
print ("Output sorteded array indices along axis 0: ", out_arr1)
out_arr2 = geek.argsort(in_arr, kind ='heapsort', axis = 1)
print ("Output sorteded array indices along axis 1: ", out_arr2)
输出:
Input array :  [[2 0 1]
 [5 4 3]]
Output sorteded array indices along axis 0:  [[0 0 0]
 [1 1 1]]
Output sorteded array indices along axis 1:  [[1 2 0]
 [2 1 0]]