Home  >  Article  >  Backend Development  >  pandas groupby grouping method to get the first few rows of records in each group

pandas groupby grouping method to get the first few rows of records in each group

不言
不言Original
2018-04-20 14:02:345735browse

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:


##classscore0a31a5 2b63b74a85a96b107c118c14

##
df.sort_values(['class','score'],ascending=[1,0],inplace=True) 
grouped = df.groupby(['class']).head(2)

grouped:


score##5aab##3 b78c147c11
##class
9 4
8 6
10
Related recommendations:
pandas multi-level grouping implementation Sorting method


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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn