Python结合Pandas Numpy按日期拆分DataFrame计算年度均值的方法
实现代码
你可以直接用pandas的分组聚合功能实现,逻辑简洁,完全匹配你要的输出结果:
import numpy as np import pandas as pd from pandas import DataFrame date_list = ['2019-09-01 00:00:00', '2019-10-01 00:00:00', '2019-11-01 00:00:00', '2019-12-01 00:00:00', '2020-01-01 00:00:00', '2020-02-01 00:00:00', '2020-03-01 00:00:00', '2020-04-01 00:00:00', '2020-05-01 00:00:00', '2020-06-01 00:00:00', '2020-07-01 00:00:00', '2020-08-01 00:00:00', '2020-09-01 00:00:00','2020-10-01 00:00:00', '2020-11-01 00:00:00', '2020-12-01 00:00:00','2021-01-01 00:00:00','2021-02-01 00:00:00', '2021-03-01 00:00:00', '2021-04-01 00:00:00','2021-05-01 00:00:00', '2021-06-01 00:00:00', '2021-07-01 00:00:00'] monthly_values = np.array([ 15., 39.6, 0.2, 34.3, 19.6, 26.8, 15.7, 26., 12.6, 15.5, 18.6, 2.3, 6.5, 2.5, 12.2, 11.6, 93.9, 25.5, 26.5, -16.5, -1.4, -1.8, 5.]) # 构造DataFrame,同时存入日期和对应月度值 df = DataFrame({ 'date': pd.to_datetime(date_list), 'value': monthly_values }) # 提取年份作为分组字段 df['year'] = df['date'].dt.year # 按年份分组求平均值,保留两位小数 year_avg = df.groupby('year')['value'].mean().round(2) # 输出结果 for year, avg in year_avg.items(): print(f"{year} Average: {avg}")
输出结果
运行后直接得到预期输出:
2019 Average: 22.28 2020 Average: 14.16 2021 Average: 18.74
如果你一定要用已有的year_changes变量做索引切片计算也可以实现,上面的方案是更通用的pandas实现,不需要手动处理索引边界,容错率更高。
内容的提问来源于stack exchange,提问作者tony selcuk
相关产品推荐
相关产品推荐

