How to get the top n rows in each group of a pandas DataFrame in Python

Getting the top n rows in each group of a pandas.DataFrame results in a new DataFrame containing only the first n rows in each group of the original.

Solution for How to get the top n rows in each group of a pandas DataFrame in Python : You can use pandas.DataFrame.groupby() and pandas.DataFrame.head() to get the top n rows in each group of a DataFrame Call pandas.DataFrame.groupby(by) to group pandas.DataFrame by the column named by. Call pandas.DataFrame.head(n) to get a new DataFrame containing only the first n rows of each group in the previous result pandas.DataFrame.


how-to-get-the-top-n-rows-in-each-group-of-a-pandas-dataframe-in-python