NumPy: Get the n largest values of an array
NumPy: Random Exercise-16 with Solution
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:
Previous: Write a NumPy program to find the closest value (to a given scalar) in an array.
Next: Write a NumPy program to create a three-dimension array with shape (300,400,5) and set to a variable. Fill the array elements with values using unsigned integer (0 to 255).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/python-numpy-random-exercise-16.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics