How to get the n-largest values of an array using NumPy?
Let’s see the program for how to get the n-largest values of an array using NumPy library. For getting n-largest values from a NumPy array we have to first sort the NumPy array using numpy.argsort() function of NumPy then applying slicing concept with negative indexing.
Syntax: numpy.argsort(arr, axis=-1, kind=’quicksort’, order=None)
Return: [index_array, ndarray] Array of indices that sort arr along the specified axis.If arr is one-dimensional then arr[index_array] returns a sorted arr.
Let’s see an example:
Example 1: Getting the 1st largest value from a NumPy array.
Python3
import numpy as np
arr = np.array([ 2 , 0 , 1 , 5 ,
4 , 1 , 9 ])
print ( "Given array:" , arr)
sorted_index_array = np.argsort(arr)
sorted_array = arr[sorted_index_array]
print ( "Sorted array:" , sorted_array)
n = 1
rslt = sorted_array[ - n : ]
print ( "{} largest value:" . format (n),
rslt[ 0 ])
|
Output:
Given array: [2 0 1 5 4 1 9]
Sorted array: [0 1 1 2 4 5 9]
1 largest value: 9
Example 2: Getting the 3-largest values from a NumPy array.
Python3
import numpy as np
arr = np.array([ 2 , 0 , 1 , 5 ,
4 , 1 , 9 ])
print ( "Given array:" , arr)
sorted_index_array = np.argsort(arr)
sorted_array = arr[sorted_index_array]
print ( "Sorted array:" , sorted_array)
n = 3
rslt = sorted_array[ - n : ]
print ( "{} largest value:" . format (n),
rslt)
|
Output:
Given array: [2 0 1 5 4 1 9]
Sorted array: [0 1 1 2 4 5 9]
3 largest value: [4 5 9]
Last Updated :
29 Aug, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...