小编atl*_*las的帖子

Pandas Groupby 多列 - 前 N 个

我有一个有趣的!我试图找到一个重复的问题,但没有成功......

我的数据框由 2013-2016 年的所有美国和领土组成,具有多个属性。

>>> df.head(2)
     state  enrollees  utilizing  enrol_age65  util_age65  year
1  Alabama     637247     635431       473376      474334  2013
2   Alaska      30486      28514        21721       20457  2013

>>> df.tail(2)
     state               enrollees  utilizing  enrol_age65  util_age65  year
214  Puerto Rico          581861     579514       453181      450150  2016
215  U.S. Territories      24329      16979        22608       15921  2016
Run Code Online (Sandbox Code Playgroud)

我想按年份和州分组,并显示每年的前 3 个州(按“登记者”或“利用”-无关紧要)。

期望输出:

                                       enrollees  utilizing
year state                                                 
2013 California                          3933310    3823455
     New York                            3133980    3002948
     Florida                             2984799    2847574
...
2016 California                          4516216    4365896
     Florida                             4186823    3984756
     New York                            4009829 …
Run Code Online (Sandbox Code Playgroud)

python pandas pandas-groupby

5
推荐指数
1
解决办法
1657
查看次数

标签 统计

pandas ×1

pandas-groupby ×1

python ×1