Pandas DataFrame nlargest() Method


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy as np 

DataFrame nlargest()

The nlargest() method retrieves and returns the first n (number) of rows containing the largest column values in descending order. This method is similar to df.sort_values().

Click here for additional details.

The syntax for this method is as follows:

DataFrame.nlargest(n, columns, keep='first')
ParameterArgument
nThis parameter is an integer that returns the specified (n) rows from a DataFrame/Series.
columnsThis parameter is a list or list of labels to order the DataFrame/Series.
keepThis parameter deals with how to handle duplicate values. The options are 'first', 'last' and 'all'.
first/last organize the first/last occurrences.
all: includes duplicates.

For this example, the countries.csv file containing nine (9) rows reads in. The top three (3) countries with the highest areas display in descending order.

πŸ’‘ Note: Click here to download this file. Move this file to the current working directory.

Code – Example 1

df = pd.read_csv('countries.csv')
result = df.nlargest(3, 'Area')
print(result)
  • Line [1] reads in a comma-delimited CSV file and saves to a DataFrame (df).
  • Line [2] determines the top three (3) countries with the highest area and sorts in descending order. The output saves to result.
  • Line [3] outputs the result to the terminal.

Output

result

 CountryCapitalPopulationArea
5RussiaMoscow146748590 17098246
6USAWashington328239523  9833520
7ChinaBeijing1400050000  9596961

For this example, the countries.csv file containing nine (9) rows reads in. The top three (3) countries with the highest areas display in descending order. In this example, the numeric fields are formatted using a lambda!

Code – Example 2

df = pd.read_csv('countries.csv')
df = df.nlargest(3, 'Population')

df['Area'] = df['Area'].apply(lambda x: '{:,}'.format(x))
df['Population'] = df['Population'].apply(lambda x: '{:,}'.format(x))
print(df)
  • Line [1] reads in a comma-delimited CSV file and saves to a DataFrame (df).
  • Line [2] determines the top three (3) countries with the highest population and sorts in descending order. The output saves to df.
  • Line [3-4] format the Population and Area columns with commas. The df updates accordingly.
  • Line [5] outputs the DataFrame to the terminal.

Output

df

 CountryCapitalPopulationArea
7ChinaBeijing1,400,050,0009,596,961
8IndiaDheli1,352,642,280 3,287,263
6USAWashington328,239,5239,833,520

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.