Python Pandas sorting after groupby and aggregate

前端 未结 1 1664
离开以前
离开以前 2021-02-14 21:26

I am trying to sort data (Pandas) after grouping and aggregating and I am stuck. My data:

data = {\'from_year\': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012]         


        
1条回答
  •  孤独总比滥情好
    2021-02-14 22:13

    You can use sort_values, but first reset_index and then set_index:

    #simplier aggregation
    days_off_yearly = persons.groupby(["from_year", "name"])['out_days'].sum()
    print(days_off_yearly)
    from_year  name 
    2010       John     17
    2011       John     15
               John1    18
    2012       John     10
               John4    11
               John6     4
    Name: out_days, dtype: int64
    
    print (days_off_yearly.reset_index()
                          .sort_values(['from_year','out_days'],ascending=False)
                          .set_index(['from_year','name']))
                     out_days
    from_year name           
    2012      John4        11
              John         10
              John6         4
    2011      John1        18
              John         15
    2010      John         17
    

    0 讨论(0)
提交回复
热议问题