-1

How do you get the top n rows of each group in a python pandas dataframe?

BigBen
  • 46,229
  • 7
  • 24
  • 40
Christos
  • 1
  • 2
  • Solution tailored from [this post](https://stackoverflow.com/questions/59437334/how-to-sample-different-number-of-rows-from-each-group-in-dataframe) about sampling n random rows from each group – Christos Mar 30 '22 at 16:31
  • Hi @BigBen, thank you for the advice! I am new to posting and practicing posting a question I had along with a solution I found – Christos Mar 30 '22 at 16:34
  • Forgive my novice knowledge on the matter. Thanks, @BigBen! – Christos Mar 30 '22 at 16:39
  • It may help you to see [ask] and also (re)take the [tour]. – BigBen Mar 30 '22 at 16:39
  • A sample dataframe and the corresponding expected output would be great. – jfaccioni Mar 30 '22 at 16:44

1 Answers1

0
n=10
top10each = df.groupby('Category').apply(lambda group: group.head(n)).reset_index(drop = True)
BigBen
  • 46,229
  • 7
  • 24
  • 40
Christos
  • 1
  • 2
  • 4
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 30 '22 at 16:46