×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Get the n largest values of an array using NumPy

In this tutorial, we will learn how to get the n largest values of an array using NumPy? By Pranit Sharma Last updated : May 23, 2023

Problem Statement

Given a NumPy array arr, and we have to get the n largest values from it. Where, n is 4.

Getting the n largest values of an array using NumPy

To get the n largest values of an array using NumPy, you can simply use we will use np.argpartition(arr, -n)[-n:]. This method is used to perform an indirect partition along the given axis using the algorithm specified by the kind keyword and returns indices array of the same shape as a that index data along the given axis in partitioned order. (Reference)

Let us understand with the help of an example,

Python program to get the n largest values of an array using NumPy

# Import numpy
import numpy as np

# Creating a Numpy array
arr = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])

# Display original numpy array
print("Original Numpy array:\n",arr,"\n")

# Defining a values for n
n = 4

# Using argpartition method for finding indices 
# of n largest values
indx = np.argpartition(arr, -n)[-n:]

# Return indices
res = arr[indx]

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Get the n largest values of an array using NumPyframe

Python NumPy Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.