简体   繁体   English

Pandas 按两列分组后对一列进行排序

[英]Pandas Sorting a column after grouping by two columns

I have a dataframe df as:我有一个 dataframe df为:

  Election Year     Votes   Vote %      Party              Region   
0   2000            42289   29.40   Janata Dal (United)     A
1   2000            27618   19.20   Rashtriya Janata Dal    A
2   2000            20886   14.50   Bahujan Samaj Party     B 
3   2000            17747   12.40   Congress                B
4   2000            14047   19.80   Independent             C
5   2000            17047   10.80   JLS                     C
6   2005            8358    15.80   Janvadi Party           A
7   2005            4428    13.10   Independent             A
8   2005            1647    1.20    Independent             B
9   2005            1610    11.10   Independent             B
10  2005            1334    15.06   Nationalist             C
11  2005            1834    18.06   NJM                     C
12  2010            21114   20.80   Independent             A
13  2010            1042    10.5    Bharatiya Janta Dal     A
14  2010            835     0.60    Independent             B
15  2010            14305   15.50   Independent             B
16  2010            22211   17.70   Congress                C
16  2010            2211    17.70   INC                     C

I have used following code to sort "Vote %" in descending order after grouping by "Election year" and "Region".在按“选举年份”和“地区”分组后,我使用以下代码按降序对“投票百分比”进行排序。 But it is giving an error.但它给出了一个错误。

df1 = df.groupby(['Election Year','Region'])sort_values('Vote %', ascending = False).reset_index()

How to correct the error as I want to get the top 3 "Party" of each region in each year after the sorting.如何纠正错误,因为我想在排序后获得每个地区每年的前 3 名“派对”。

You can perform the grouping and the in-group sorting through sort itself:您可以通过sort本身执行分组和组内排序:

df1 = df.sort_values(['Election Year','Region', 'Vote %'], ascending=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM