search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Getting the top n rows with largest column value in each group in Pandas

schedule Aug 12, 2023
Last updated
local_offer
PythonPandas
Tags
tocTable of Contents
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Example

Consider the following DataFrame about some products:

df = pd.DataFrame({"price":[500,300,700, 200,900], "brand": ["apple", "google", "apple", "google","apple"], "device":["phone","phone","computer","phone","phone"]}, index=["a","b","c","d","e"])
df
price brand device
a 500 apple phone
b 300 google phone
c 700 apple computer
d 200 google phone
e 900 apple phone

Solution

To get the top 2 priciest products of each brand:

df.sort_values("price", ascending=False).groupby("brand").head(2) # returns a DataFrame
price brand device
e 900 apple phone
c 700 apple computer
b 300 google phone
d 200 google phone

Explanation

We first sort by price in descending order using sort_values(~):

df.sort_values("price", ascending=False)
price brand device
e 900 apple phone
c 700 apple computer
a 500 apple phone
b 300 google phone
d 200 google phone

Next, we group by brand, and the key here is that groupby(~) preserves order. This means that even after we group by brand, the rows in every group will still be sorted by price. For this very reason, calling head(2) would return the 2 priciest device in each group.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
3
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!