按groupby和aggreg排序的Python Pandas

2024-09-29 21:36:46 发布

您现在位置:Python中文网/ 问答频道 /正文

在分组和聚合之后,我试图对数据(Pandas)进行排序,但我陷入了困境。我的数据:

data = {'from_year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
    'name': ['John', 'John1', 'John', 'John', 'John4', 'John', 'John1', 'John6'],
    'out_days': [11, 8, 10, 15, 11, 6, 10, 4]}
persons = pd.DataFrame(data, columns=["from_year", "name", "out_days"])

days_off_yearly = persons.groupby(["from_year", "name"]).agg({"out_days": [np.sum]})

print(days_off_yearly)

之后,我对我的数据进行排序:

                out_days
                     sum
from_year name          
2010      John        17
2011      John        15
          John1       18
2012      John        10
          John4       11
          John6        4

我想按“年”和“天”的总和对数据进行排序,并期望数据为:

                out_days
                     sum
from_year name          
2012      John4       11
          John        10
          John6        4    
2011      John1       18
          John        15
2010      John        17

我在努力

print(days_off_yearly.sort_values(["from_year", ("out_days", "sum")], ascending=False).head(10))

但得到的关键错误:“从'年'。

感谢任何帮助。


Tags: 数据namefromdata排序outjohndays
1条回答
网友
1楼 · 发布于 2024-09-29 21:36:46

您可以使用^{},但首先使用reset_index,然后使用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

相关问题 更多 >

    热门问题