首页 > 解决方案 > Pandas DF 按月和日计算的所有年份平均值

问题描述

我在名为“aodata”(25627,4)的 df 中有这样的数据

       Year  Month Day  Index
0      1950      1   1 -2.511
1      1950      1   2 -1.505
2      1950      1   3 -1.173
3      1950      1   4 -1.251
4      1950      1   5 -0.126
...    ...  ..    ...
25622  2020      2  25  1.836
25623  2020      2  26  1.724
25624  2020      2  27  2.151
25625  2020      2  28  1.848
25626  2020      2  29  1.741

我需要找到“索引”列的长期每日平均值(来自所有年份),以便我的输出在特定月份(如 2 月)(月份 ==2)看起来像这样:

Month Day AvgIndex
2   1   -5.43
2   2   -5.29
2   3   -4.15
... ... ...
2   29   3.46

我尝试了不同的组合

cmao_mean = aodata[(aodata.Month == month)&(aodata.Day)].Index.mean() #gives a single number of the average of all the days in the month. 

而且,我试图用这样的 for 循环来做到这一点:

days = list(range(1,29))
for x in days:
     dmao = aodata[(aodata.Month == month)&(aodata.Day)].Index.mean(x)

这给了我这样的错误:

ValueError: No axis named 1 for object type <class 'pandas.core.series.Series'>

我是 Python 新手,但我正在学习。感谢您对此的任何帮助!

标签: pythonloopsdataframeaveragedays

解决方案


推荐阅读