numpy.argsort() v Pythonu

numpy.argsort() Funkce se používá k provedení nepřímého řazení podél dané osy pomocí algoritmu určeného klíčovým slovem kind. Vrací pole indexů stejného tvaru jako arr, které by pole seřadilo. Znamená indexy hodnoty uspořádané vzestupně

Syntaxe: numpy.argsort(arr, osa=-1, druh='rychlé řazení', objednávka=Žádné)

Parametry:

    arr : [array_like] Vstupní pole. osa : [int nebo žádná] Osa, podle které se má třídit. Pokud je žádné, pole se před řazením sloučí. Výchozí hodnota je -1, která třídí podle poslední osy. druh : [‘quicksort’, ‘mergesort’, ‘heapsort’]Algoritmus výběru. Výchozí je „rychlé řazení“. order : [str nebo seznam str] Když arr je pole s definovanými poli, tento argument určuje, která pole se mají porovnat jako první, druhá atd.

Vrátit se: [index_array, ndarray] Pole indexů, které třídí arr podél zadané osy. Pokud je arr jednorozměrné, pak arr[index_array] vrací seřazené pole arr.

Kód #1:

Python3




# 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])>

Výstup:

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] 

Kód #2:

Python3




# 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 sorted 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)>

Výstup:

Input array : [[2 0 1] [5 4 3]] Output sorted array indices along axis 0: [[0 0 0] [1 1 1]] Output sorted array indices along axis 1: [[1 2 0] [2 1 0]] 

Kód #3:

Krajta




# get two largest value from numpy array> x> => np.array([> 12> ,> 43> ,> 2> ,> 100> ,> 54> ,> 5> ,> 68> ])> # using argsort get indices of value of arranged in ascending order> np.argsort(x)> #get two highest value index of array> np.argsort(x)[> -> 2> :]> # to arrange in ascending order of index> np.argsort(x)[> -> 2> :][::> -> 1> ]> # to get highest 2 values from array> x[np.argsort(x)[> -> 2> :][::> -> 1> ]]>

Výstup:

array([2, 5, 0, 1, 4, 6, 3], dtype=int32) array([6, 3], dtype=int32) array([3, 6], dtype=int32) array([100, 68])