【问题标题】:Find largest 2 values for each year in the returned pandas groupby object after sorting each group在对每个组进行排序后,在返回的 pandas groupby 对象中查找每年的最大 2 个值
【发布时间】:2020-04-13 20:03:55
【问题描述】:

我的数据框有 3 列:年份。主因,死亡。我想找出每年的主要死因死亡总数。我做了以下事情: totalDeaths_Cause = df.groupby(["Year", "Leading Cause"])["Deaths"].sum() 这导致:

The total number of deaths for :

 Year  Leading Cause          
2009  Hypertension                 26
2010  All Other Causes           2140
2011  Cerebrovascular Disease     281
      Immunodeficiency             70
      Parkinson Disease           180
2012  Cerebrovascular Disease     102
      Disease1                    183
      Diseases of Heart            76
2013  Cerebrovascular Disease     386
      Parkinson Disease           372
      Self-Harm                    17
Name: Deaths, dtype: int64

现在我想获得每年最大的 2 个值(用于死亡)和主要的原因:

The total number of deaths for :

 Year  Leading Cause          
2009  Hypertension                 26
2010  All Other Causes           2140
2011  Cerebrovascular Disease     281
      Parkinson Disease           180
2012  Disease1                    183
      Cerebrovasular disease      102
2013  Cerebrovascular Disease     386
      Parkinson Disease           372

提前感谢您的帮助!

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    让我们做吧

    df=df.sort_values().groupby(level=0).tail(1)
    

    【讨论】:

    • TypeError: sort_values() 缺少 1 个必需的位置参数:'by'
    • 对不起。纠正了错误,但现在我得到了结果:
    • 没有2011的
    • 2009 年主要病因 26 2012 疾病 1 183 2013 脑血管疾病 386 2010 所有其他原因 2140 名称:死亡,数据类型:int64
    • @bipvan 你有系列或数据框
    猜你喜欢
    • 2020-04-20
    • 1970-01-01
    • 2016-07-23
    • 2020-02-22
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多