如何对DataFrame中的日度数据按年月分组求和或计算均值?
Pandas 按年月汇总日度降水数据实现方案
下面两种方法都可以快速实现需求:
- 前置操作:先确保date列为datetime格式,若该列已经是datetime类型可以跳过本步骤
代码:import pandas as pd df['date'] = pd.to_datetime(df['date'])
方法1:分组聚合(逻辑最直观)
直接按年、月维度分组后对降水量求和,一行代码就能出结果:
result = df.groupby( [df['date'].dt.year.rename('year'), df['date'].dt.month.rename('month')] )['precip'].sum().reset_index(name='sum_precip')
方法2:时间重采样(适合时间序列类处理场景)
先将日期设为索引,用重采样函数按月维度求和,再拆分出年、月字段即可:
# 按月重采样求和 monthly_sum = df.set_index('date').resample('M')['precip'].sum().reset_index() # 拆分年月字段并重命名 monthly_sum['year'] = monthly_sum['date'].dt.year monthly_sum['month'] = monthly_sum['date'].dt.month result = monthly_sum[['year', 'month', 'precip']].rename(columns={'precip': 'sum_precip'})
两种方法输出的结果完全匹配你要求的结构,直接使用即可。
内容的提问来源于stack exchange,提问作者user17357507
相关产品推荐
相关产品推荐

