如何修正groupby后的计数?实现各时段各Section全量统计(含0值)
解决方案
要实现每小时各Section的计数(含0值),核心是先构建所有小时-Section的完整组合,再和原统计结果做左连接填充空值。具体步骤如下:
- 确保
Date列为datetime类型(如果原数据不是的话):
df['Date'] = pd.to_datetime(df['Date'])
- 提取所有唯一的Section类别,生成覆盖原数据时间范围的完整小时序列:
# 获取所有不重复的Section sections = df['Section'].unique() # 生成从最早时间整点到最晚时间整点的小时序列 date_range = pd.date_range( start=df['Date'].min().floor('H'), end=df['Date'].max().ceil('H'), freq='H' )
- 构建包含所有小时-Section组合的全量DataFrame:
# 生成多索引的笛卡尔积 full_index = pd.MultiIndex.from_product( [date_range, sections], names=['Date', 'Section'] ) full_df = pd.DataFrame(index=full_index).reset_index()
- 执行原分组统计,再和全量DataFrame左连接,空值填充为0:
# 原分组统计逻辑 new_df = df.groupby( [pd.Grouper(key='Date', freq='H'), 'Section'] ).agg(PPT=('Section', 'count')).reset_index() # 左连接并填充0值 result = full_df.merge(new_df, on=['Date', 'Section'], how='left').fillna({'PPT': 0})
这样得到的result就会包含每小时每个Section的计数,哪怕该小时对应Section没有条目,也会显示PPT=0。
注意:如果原
Date列带时区,需要在生成date_range时指定tz参数,保持时区一致。
内容的提问来源于stack exchange,提问作者Very_new_to_this
相关产品推荐
相关产品推荐

