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

按截止日期汇总DataFrame的score列数值及groupby代码问题

解决按日期截止汇总score的问题

你的代码存在的问题

  1. 拼写错误:gropuby 应为 groupby
  2. 日期比较逻辑错误:无法直接用字符串做日期大小比较,且布尔索引的写法不符合Pandas语法
  3. 不必要的groupby:你的需求是按日期区间汇总score总和,不需要按score分组

正确实现步骤

  1. 转换日期列格式:Pandas的日期比较必须基于datetime类型,先把date列转为标准日期格式
  2. 定义统一截止日期:将截止日期也转为datetime类型,避免字符串比较的隐患
  3. 按区间筛选求和:分别筛选截止日期前后的数据,计算score总和,无有效数据时按需求显示--

完整代码示例

import pandas as pd

# 示例数据
data = {
    'date': ['2020-01-5', '2020-02-10', '2020-02-19', '2020-03-17', '2020-03-20'],
    'score': [0, 1, 1, 0, 1]
}
df = pd.DataFrame(data)

# 1. 转换date列为datetime类型
df['date'] = pd.to_datetime(df['date'])

# 2. 定义截止日期
cutoff_date = pd.to_datetime('2020-02-19')

# 3. 计算截止日期之前(不含当天)的score总和
before_cutoff = df[df['date'] < cutoff_date]['score'].sum()

# 4. 计算截止日期之后(不含当天)的score总和,无数据时显示--
after_cutoff = df[df['date'] > cutoff_date]['score'].sum()
after_cutoff = after_cutoff if after_cutoff != 0 else '--'

# 输出结果
print(f'before_cutoff= {before_cutoff}')
print(f'after_cutoff= {after_cutoff}')

输出结果

before_cutoff= 1
after_cutoff= 1

(注:若实际数据中截止日期之后无有效score数据,after_cutoff会自动显示--)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:23:32