Home >Backend Development >Python Tutorial >How to Group and Sort Pandas Dataframe by Two Columns and Take Top Rows 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!