Find n largest values of a NumPy array in Python

In this post, you will learn how to find the n-largest values of a NumPy array in Python. Now, what should be the first step to get the number? We want our data or array to be sorted. Our approach for this should be the sorting and negative indexing method. The code should be pretty straightforward. Let us now see this with an example.

The numpy.argsort function:

This function provided by the NumPy library allows the user to sort any given array of integers. This function returns us the sorted array.

import numpy as np

array = np.array([2,5,3,3,2,1,6])

print("The given array:", array)

sortedarray = np.argsort(array)

# sorted array
sorted_array = array[sortedarray]

print("Sorted array:", sorted_array)

n = 3

result = sorted_array[-n : ]

print("{} largest value:".format(n), result[0])
  1. In this above program, we import the NumPy library.
  2. After that, we enter an array of integers and store them in a variable.
  3. We sort that array and print it.
  4. We define the value of N.
  5. Using negative indexing in Python.
  6. Printing the largest value in the array.

Output:

The given array: [2 5 3 3 2 1 6]
Sorted array: [1 2 2 3 3 5 6]
1 largest value: 6

With the above steps, we can find the largest numbers of any given array.

Python code to find n largest values of a NumPy array

import numpy as np

array = np.array([2,5,3,3,2,1,6])

print("The given array:", array)

sortedarray = np.argsort(array)

# sorted array
sorted_array = array[sortedarray]

print("Sorted array:", sorted_array)

n = 3


result = sorted_array[-n : ]

print("{} largest value:".format(n), result)

Here we will print the largest 3 numbers by defining n = 3.

Output:

The given array: [2 5 3 3 2 1 6]
Sorted array: [1 2 2 3 3 5 6]
3 largest value: [3 5 6]

Leave a Reply

Your email address will not be published. Required fields are marked *