The following is a pandas groupby method for grouping and recording the first few rows of each group. It has a good reference value and I hope it will be helpful to everyone. Let’s come and take a look.
Let’s go straight to the example.
import pandas as pd df = pd.DataFrame({'class':['a','a','b','b','a','a','b','c','c'],'score':[3,5,6,7,8,9,10,11,14]})
df:
score | ||
---|---|---|
a | 3 | |
a | 5 | |
b | 6 | |
b | 7 | |
a | 8 | |
a | 9 | |
b | 10 | |
c | 11 | |
c | 14 |
df.sort_values(['class','score'],ascending=[1,0],inplace=True) grouped = df.groupby(['class']).head(2)
grouped:
##class | score||
---|---|---|
9 | 4 | |
8 | 6 | |
10 | ##3 | b |
8 | c | |
7 | c | |
Related recommendations: |
pandas method of getting the row with the maximum value in the groupby group
Getting started with Python data processing library pandas
The above is the detailed content of pandas groupby grouping method to get the first few rows of records in each group. For more information, please follow other related articles on the PHP Chinese website!