w3resource

NumPy: Get the n largest values of an array


16. n Largest Values in 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:

NumPy Random: Get the n largest values of an array

For more Practice: Solve these Related Problems:

  • Write a function that extracts the n largest elements from a 1D array using np.partition and sorts them in descending order.
  • Create a solution that returns both the n largest values and their original indices.
  • Implement an algorithm that finds the n largest elements without using built-in functions and compares the results.
  • Test the function on arrays with duplicate values to ensure that the n largest unique values are correctly identified.

Go to:


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).

Python-Numpy Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.