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

pandas使用groupby分组时如何输出统计值为0的分组项

pandas分组统计补全缺失类别0值的实现方案

完整修改代码

import pandas as pd

df = pd.read_csv('climate_data_Dec2017.csv')
# 提取全量数据中所有唯一风向类别作为输出全集
all_wind_dirs = df['Direction of maximum wind gust'].unique()

# 筛选12月26日的观测数据
specific_day = df[df['Date'].str.contains("12-26")]

# 统计单日各风向的记录数
single_day_count = specific_day.groupby('Direction of maximum wind gust').size()
# 重索引对齐全量风向,缺失值填充为0
full_count = single_day_count.reindex(all_wind_dirs, fill_value=0)

print(full_count)

核心逻辑说明

  • 提前获取全量数据集的所有风向类别,避免仅使用单日数据导致类别缺失
  • 利用pandas的reindex()方法,将单日统计结果的索引和全量风向列表对齐,未匹配到的类别自动填充设置的0值
  • 如果需要固定风向的输出顺序,可以手动定义全量风向列表:
# 手动定义16风向全集与排序
all_wind_dirs = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW']
full_count = single_day_count.reindex(all_wind_dirs, fill_value=0)

内容的提问来源于stack exchange,提问作者Mathhurtsmybrain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:57:03