Home  >  Article  >  Backend Development  >  How to Group and Sort Pandas Dataframe by Two Columns and Take Top Rows Within Groups?

How to Group and Sort Pandas Dataframe by Two Columns and Take Top Rows Within Groups?

DDD
DDDOriginal
2024-10-20 17:20:29716browse

How to Group and Sort Pandas Dataframe by Two Columns and Take Top Rows Within Groups?

pandas groupby and sorting within groups

This question asks how to group a pandas dataframe by two columns and then sort the aggregated results within those groups. The desired output is to take only the top three rows of each group.

One way to do this is by sorting the dataframe by the desired columns, grouping it, and then taking the head of each group. The code to do this is:

<code class="python">df.sort_values(['job','count'],ascending=False).groupby('job').head(3)</code>

This will produce the following output:

   count     job source
4      7   sales      E
2      6   sales      C
1      4   sales      B
5      5  market      A
8      4  market      D
6      3  market      B

The above is the detailed content of How to Group and Sort Pandas Dataframe by Two Columns and Take Top Rows Within Groups?. 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