[PYTHON] Extract N samples for each group with Pandas DataFrame

I want to extract N pieces for each group, and one of the countermeasures. For example, when you want to extract the daily column and the top nth sales.

sort_values Sorting groupby Grouping .head(n) N from the beginning in the group .tail() N from behind in the group

Sample code: Up to the top 3 in sales

newdf = df.sort_values(by=['date','Sales'], ascending=[True, False]).groupby('date').head(3)

 Reference article:

Recommended Posts

Extract N samples for each group with Pandas DataFrame
Standardize by group with pandas
Pandas / DataFrame Tips for practical use
Extract the maximum value with pandas.
Extract specific multiple columns with pandas
Manipulating strings with pandas group by
Bulk Insert Pandas DataFrame with psycopg2
Create an age group with pandas
Feature generation with pandas group by
Limit ssh with iptables for each user
Tips for plotting multiple lines with pandas
Replace column names / values with pandas dataframe
Best practices for messing with data with pandas
Invert pandas DataFrame upside down with just 15 characters without using a for statement
How to replace with Pandas DataFrame, which is useful for data analysis (easy)
Pandas basics for beginners ③ Histogram creation with matplotlib
Create execution environment for each language with boot2docker
Python pandas: Search for DataFrame using regular expressions
Delete rows with arbitrary values in pandas DataFrame
Remove rows with duplicate indexes in pandas DataFrame
Rollback DB for each test with Flask + SQLAlchemy