Pandas DataFrame nsmallest() Method

Rate this post

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 nsmallest()

The nsmallest() method retrieves and returns the first n (number) of rows that contain the smallest column values in ascending order.

The syntax for this method is as follows:

DataFrame.nsmallest(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.
N:This parameter is an integer and returns the specified (n) rows from a DataFrame/Series.
Columns:This parameter is a list or list of labels to order the DataFrame/Series.
Keep:This 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 finxters.csv file containing fictitious Finxter user information reads in. The users with the smallest number of puzzles solved returns in ascending order. In this example, the numeric fields are formatted using a lambda.

df = pd.read_csv('finxters.csv')
df = df.nsmallest(3, 'Solved')

df['Solved'] = df['Solved'].apply(lambda x: '{:,}'.format(int(x)))
df['Incorrect'] = df['Incorrect'].apply(lambda x: '{:,}'.format(int(x)))
df['Recurring'] = df['Recurring'].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 three (3) users with the smallest number of puzzles solved and sorts in ascending order. The output saves to df.
  • Line [3-4] converts to an integer and formats the Solved and Incorrect columns with commas. The df updates accordingly.
  • Line [5] formats the Recurring column with a dollar sign and a comma. The df updates accordingly.
  • Line [6] outputs the DataFrame to the terminal.

Output

 FIDStartFirst_NameLast_Name…SolvedIncorrectRecurringTaxes
230022331 11/1/2021PeterDunn β€¦1599.9815
183002285 16/6/2021Jack Thompson β€¦911815.9818
4230024622 6/10/2021Jan   Martin β€¦995379.9810

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.