按截止日期汇总DataFrame的score列数值及groupby代码问题
解决按日期截止汇总score的问题
你的代码存在的问题
- 拼写错误:
gropuby应为groupby - 日期比较逻辑错误:无法直接用字符串做日期大小比较,且布尔索引的写法不符合Pandas语法
- 不必要的
groupby:你的需求是按日期区间汇总score总和,不需要按score分组
正确实现步骤
- 转换日期列格式:Pandas的日期比较必须基于datetime类型,先把
date列转为标准日期格式 - 定义统一截止日期:将截止日期也转为datetime类型,避免字符串比较的隐患
- 按区间筛选求和:分别筛选截止日期前后的数据,计算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
相关产品推荐
相关产品推荐

