How to calculate top 5 max values in Pandas

Aggregation of fields is one of the basic necessity for data analysis and data science. Python’s Pandas module provide easy ways to do aggregation and calculate metrics. Finding Top 5 maximum value for each group can also be achieved while doing the group by. The function that is helpful for finding the Top 5 maximum value is nlargest(). The below article explains with the help of an example How to calculate Top 5 max values by Group in Pandas Python.

John has store sales data available for analysis. There are five columns present in the data, Geography (country of store), Department (Industry category of the store), StoreID (Unique ID of each store), Time Period (Month of sales), Revenue (Total Sales for the month). John is looking forward to calculate Top 5 maximum revenue for each Geography.

How to calculate top 5 max values in Pandas

Top 5 max values in Pandas

  • Step 1: Firstly, Import all the necessary modules.
import pandas as pd
  • Step 2: Use nlargest() function along with groupby operation. As we are looking forward to group by each Geography, by=”Geography” works as groupby parameter. The Revenue field contains the sales of each Geography. To find the top 5 maximum value, we will be using “Revenue” for value calculation. For the current example, syntax is:
df1.groupby(by="Geography")["Revenue"].nlargest(5)
How to calculate top 5 max values in Pandas

Example 2: Top 5 max values for each Month / Time Period

  • Here we are looking forward to calculate the top 5 max value across each time period. So, the field in groupby operation will be “Time Period”
df1.groupby(by="Time Period")["Revenue"].nlargest(5)
How to calculate top 5 max values in Pandas

Thus, John is able to calculate values as per his requirement in Python.

To get top certifications in Python and build your resume visit here. Also, you can read books listed here to build strong knowledge around Python.

Visit us below for video tutorial:

πŸ“¬ Stay Ahead in Data Science & AI – Subscribe to Newsletter!

  • 🎯 Interview Series: Curated questions and answers for freshers and experienced candidates.
  • πŸ“Š Data Science for All: Simplified articles on key concepts, accessible to all levels.
  • πŸ€– Generative AI for All: Easy explanations on Generative AI trends transforming industries.

πŸ’‘ Why Subscribe? Gain expert insights, stay ahead of trends, and prepare with confidence for your next interview.

πŸ‘‰ Subscribe here:

Related Posts

One thought on “How to calculate top 5 max values in Pandas

  1. It抯 really a great and helpful piece of information. I抦 happy that you shared this useful information with us. Please keep us informed like this. Thank you for sharing.

Comments are closed.