pandas 分组并同时对列进行排序 [英] Pandas Groupby and sorting columns simultaneously

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

问题描述

我有一个数据帧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            20011   14.70   INC                     C

如何才能获得每个选举年两个或两个以上政党得票率超过10%的地区列表?

我使用以下代码在按";选举年";和";地区";分组后按降序对";Vote%&Quot;进行排序,然后每年比较前2个投票率%,但出现错误。

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

如何纠错,因为我想在排序后得到每个地区每年的前2名政党,然后看看他们在每个选举年的得票率是否超过10%?

所需输出:

Election Year    Region    Vote %
  2000             A        29.40
  2000             A        19.40
  2000             C        19.80
  2000             C        10.80
  2005             A        15.80
  2005             A        13.10
  2005             C        15.06
  2005             C        18.06
  2010             A        20.80
  2010             A        10.5
  2010             C        17.70
  2010             C        14.70

输出只包含每年投票率超过10%的地区,选举年份和地区名称按升序排序。因此,这里只有区域&Q;A&Q;和&Q;C&Q;将出现在输出中。

推荐答案

首先使用sort_values()对值w.r.t";vot%";进行排序,然后使用groupby";选举年份&报价;和";区域&报价;排序,最后使用head(2)

获得前两行
df.sort_values(['Vote %'],ascending=False).groupby(['Election Year','Region']).head(2).reset_index(drop=True)

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

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