You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修正groupby后的计数?实现各时段各Section全量统计(含0值)

解决方案

要实现每小时各Section的计数(含0值),核心是先构建所有小时-Section的完整组合,再和原统计结果做左连接填充空值。具体步骤如下:

  1. 确保Date列为datetime类型(如果原数据不是的话):
df['Date'] = pd.to_datetime(df['Date'])
  1. 提取所有唯一的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'
)
  1. 构建包含所有小时-Section组合的全量DataFrame:
# 生成多索引的笛卡尔积
full_index = pd.MultiIndex.from_product(
    [date_range, sections],
    names=['Date', 'Section']
)
full_df = pd.DataFrame(index=full_index).reset_index()
  1. 执行原分组统计,再和全量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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:40:25