How to get topmost N records within each group of a Pandas DataFrame?

Given a Pandas DataFrame, we have to get topmost N records within each group.
Submitted by Pranit Sharma, on June 04, 2022

Rows in pandas are the different cell (column) values which are aligned horizontally and also provides uniformity. Each row can have same or different value. Rows are generally marked with the index number but in pandas we can also assign index name according to the needs.

Here, we are going to learn how to get the topmost N records within each group, for this purpose we will first use pandas.DataFrame.groupby() and then we will select topmost N record by using the following piece of code with the groupby result,


To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

# Importing pandas package
import pandas as pd

# Create dictionary
d = {

# Create DataFrame
df = pd.DataFrame(d)

# Display DataFrame
print("Created DataFrame:\n",df)

# Groupby function
result = df.groupby('a', as_index=False)

# Selecting 1st row of group by result
final = result.head(2).reset_index(drop=True)

# Display final result
print("Final result:\n",final)

Original DataFrame:

Example 1: Get topmost N records within each group

Topmost N records in groupby result:

Example 2: Get topmost N records within each group

Python Pandas Programs »


Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.