熊猫按两列分组后对列进行排序

时间:2021-06-09 23:20:27

标签: python pandas dataframe pandas-groupby columnsorting

我有一个数据框 df as:

  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

我使用以下代码在按“选举年”和“地区”分组后按降序对“投票百分比”进行排序。但它给出了一个错误。

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

如何更正错误,因为我想在排序后获得每年每个地区的前3个“派对”。

1 个答案:

答案 0 :(得分:0)

您可以通过sort本身进行分组和组内排序:

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