NumPy: Get the n largest values of an array
Write a NumPy program to get the n largest values of an array.
Sample Solution:
Python Code:
# Importing the NumPy library as np
import numpy as np
# Creating an array 'x' containing numbers from 0 to 9 using arange() function
x = np.arange(10)
# Displaying the original array 'x'
print("Original array:")
print(x)
# Shuffling the elements in array 'x'
np.random.shuffle(x)
# Selecting the 'n' largest elements in 'x' using argsort and slicing
n = 1
print(x[np.argsort(x)[-n:]])
Sample Output:
Original array: [0 1 2 3 4 5 6 7 8 9] [9]
Explanation:
In the above exercise –
x = np.arange(10): This statement generates a 1D array of integers from 0 to 9 (inclusive).
np.random.shuffle(x): This statement shuffles the elements of the array x in-place (i.e., the original array is modified) in a random order.
n = 1: This statement sets the variable n to 1, which represents the number of largest elements we want to extract from the shuffled array.
x[np.argsort(x)[-n:]]: This statement sorts the indices of the shuffled array x using np.argsort(x) in ascending order. Then, by slicing [-n:], we get the last n indices corresponding to the n largest elements in the array. In this case, since n = 1, the slice returns the index of the largest element in the shuffled array.
print(x[np.argsort(x)[-n:]]): Finally print() function prints the largest element in the shuffled array by indexing the array x with the calculated slice.
Pictorial Presentation:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics