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

Pandas使用groupby(index.floor('D')).sum()计算日总和结果异常问题

问题:DataFrame按日求和结果异常(全为0且有效数值丢失)

问题背景

我有一个名为df_insitu的DataFrame,包含GPP_uStar_f列,截取的前20条数据如下:

datetime
2011-01-01 02:00:00        -0.0
2011-01-01 05:00:00        -0.0
2011-01-01 06:00:00        -0.0
2011-01-01 07:00:00        -0.0
2011-01-01 08:00:00        -0.0
2011-01-01 10:00:00   -0.019085
2011-01-01 13:00:00        -0.0
2011-01-01 15:00:00        -0.0
2011-01-05 06:00:00        -0.0
2011-01-05 19:00:00        -0.0
2011-01-05 20:00:00        -0.0
2011-01-06 03:00:00        -0.0
2011-01-06 05:00:00        -0.0
2011-01-06 08:00:00        -0.0
2011-01-06 12:00:00   -0.024992
2011-01-06 15:00:00        -0.0
2011-01-06 16:00:00        -0.0
2011-01-06 17:00:00        -0.0
2011-01-06 19:00:00        -0.0
2011-01-06 21:00:00        -0.0
Name: GPP_uStar_f, dtype: object

执行以下代码可得到正确日总和:

df_test = df_insitu.GPP_uStar_f[(df_insitu.index.year == 2011) & (df_insitu.index.month == 1)].iloc[0:20].copy()
print(df_test.groupby(df_test.index.floor('D')).sum())

结果:

datetime
2011-01-01   -0.019089
2011-01-05   -0.000002
2011-01-06   -0.024996
Name: GPP_uStar_f, dtype: object

但执行df_plot.GPP_uStar_f.groupby(df_plot.GPP_uStar_f.index.floor('D')).sum()时,结果全为0且2011-01-01的有效数值丢失,请问原因是什么?

可能的原因分析

  • 数据类型不匹配:原数据GPP_uStar_f列的 dtype 是object,df_test直接截取原数据子集,求和时能自动解析其中的数值型字符串;但df_plot可能在预处理过程中,把该列的有效数值(如-0.019085)转换成了无法被求和识别的类型(比如纯字符串、空值或非数值对象),导致求和时全部按0计算。
  • 数据预处理差异:df_plot和df_test的数据源或预处理步骤不同——比如df_plot中2011-01-01 10:00:00的那条有效数据被过滤、替换成0,或者被误标记为缺失值并填充为0。
  • 索引类型异常:如果df_plot的索引不是datetime类型(比如被转换成了字符串),index.floor('D')会无法正确生成日期分组键,导致分组逻辑错误,最终求和结果异常。
  • 缺失值处理错误:若df_plot在预处理时错误地将有效数值当作缺失值填充为0,或者将本该保留的数值丢弃,就会出现全0求和结果。

验证方法

可以通过以下代码排查问题:

  1. 检查df_plot.GPP_uStar_f的数据类型和前20条数据:
print(df_plot.GPP_uStar_f.dtype)
print(df_plot.GPP_uStar_f.head(20))
  1. 验证分组键是否正确生成:
print(df_plot.GPP_uStar_f.index.floor('D').unique())
  1. 检查单条有效数据是否存在:
print(df_plot.loc['2011-01-01 10:00:00', 'GPP_uStar_f'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:12:46