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

DDD
Release: 2024-10-20 17:20:29
Original
715 people have browsed it

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>
Copy after login

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
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!