pandas 按两列分组后对列进行排序 [英] Pandas Sorting a column after grouping by two columns

查看:79
本文介绍了 pandas 按两列分组后对列进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框 df 为:

I have a dataframe dfas:

  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

我使用以下代码对Vote %"进行排序;按选举年"分组后降序排列和地区".但它给出了一个错误.

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()

如何纠正错误,因为我想获得前 3 个派对"排序后每年各地区.

How to correct the error as I want to get the top 3 "Party" of each region in each year after the sorting.

推荐答案

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

You can perform the grouping and the in-group sorting through sort itself:

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

这篇关于 pandas 按两列分组后对列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆