Overview
- Largest 'n' numbers and smallest 'n' numbers from a Pandas series can be obtained through the methods nlargest() and nsmallest().
- Both the methods, nsmallest() and nlargest() return a pandas series.
- The original index from the main series is retained in the new series returned by nsmallest() and nlargest() methods.
Example – Getting ‘n’ smallest numbers from a Pandas Series
# Example Python program to get the n smallest numbers from a Pandas series
import pandas as pds
# List of numbers
listOfNums = [5, 1, 10, 15, 75, 40, 35, 65, 70];
# Create a pandas Series
series = pds.Series(listOfNums);
# Get a series with three smallest numbers from the main series
nSmallSeries3 = series.nsmallest(3);
# Get a series with five smallest numbers from the main series
nSmallSeries5 = series.nsmallest(5);
print("Series obtained with 3 smallest numbers:");
print(nSmallSeries3);
print("Series obtained with 5 smallest numbers:");
print(nSmallSeries5);Output
Series obtained with 3 smallest numbers:
1 1
0 5
2 10
dtype: int64
Series obtained with 5 smallest numbers:
1 1
0 5
2 10
3 15
6 35
dtype: int64Example – Getting ‘n’ largest numbers from a Pandas Series
# Example Python program to get the n largest numbers from a Pandas series
import pandas as pds
tupleOfNumbers = (0.1, 0.4, 0.2, 0.7, 0.6, 0.8, 1.2, 0.75, 0.05, 0.15);
series = pds.Series(tupleOfNumbers);
series4Large = series.nlargest(4);
series6Large = series.nlargest(6);
print("Series with four largest elements from the original series:");
print(series4Large);
print("Series with six largest elements from the original series:");
series6Large = series.nlargest(6);
print(series6Large);Output
Series with four largest elements from the original series:
6 1.20
5 0.80
7 0.75
3 0.70
dtype: float64
Series with six largest elements from the original series:
6 1.20
5 0.80
7 0.75
3 0.70
4 0.60
1 0.40
dtype: float64