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

如何对以datetime为键的数据集按日小时分组求取对应值的最大值?

按小时提取每日数据最大值的解决方案

需求说明

处理CSV文件,以YYYY-MM-DD HH格式的日期时间为分组键,提取每个小时分组内对应数值的最大值。

原始数据示例

2022-11-03 00,1.76074
2022-11-03 00,1.9003
2022-11-03 01,2.0195
2022-10-03 01,2.4589
2022-10-03 01,2.5791
2022-10-03 05,2.719743
2022-10-03 05,3.8798828

日期时间格式说明

  • 2022:年份
  • 10/11:月份
  • 03:日期
  • 00/01/05:小时

预期输出结果

2022-11-03 00,1.9003
2022-10-03 01,2.5791
2022-10-03 05,3.8798828

原代码问题分析

你提供的代码存在两个核心问题:

  1. 日期解析格式错误:原始数据是YYYY-MM-DD HH,但代码用了带秒和毫秒的格式%Y-%m-%d %H:%M:%S.%f,导致解析失败
  2. 逻辑错误:代码实现的是求和而非需求的取最大值
  3. 文件操作未使用安全的with语句,可能导致资源泄漏

原错误代码:

import datetime
sum_values_by_hour = {}

content = open('M2.csv', 'r') 
result = open('M2_new.csv', 'w')
for line in content:
    line = line.strip().split(',')
    line_1 = datetime.datetime.strptime(line[1], '"%Y-%m-%d %H:%M:%S.%f"')
    period = line_1.strftime("%Y-%m-%d %H")
    if period not in sum_values_by_hour:
        sum_values_by_hour[period] = float(line[2])
    else:
        sum_values_by_hour[period]  += float(line[2])
    result.write(period + ',' + str(sum_values_by_hour[period]) + '\n')

修正后的代码

import datetime

max_values_by_hour = {}

# 使用with语句自动管理文件打开/关闭
with open('M2.csv', 'r') as content, open('M2_new.csv', 'w') as result:
    for line in content:
        line = line.strip()
        if not line:
            continue  # 跳过空行
        dt_str, value_str = line.split(',')
        current_value = float(value_str)
        
        # 匹配原始数据的日期格式解析
        dt = datetime.datetime.strptime(dt_str, "%Y-%m-%d %H")
        period = dt.strftime("%Y-%m-%d %H")
        
        # 更新当前小时段的最大值
        if period not in max_values_by_hour:
            max_values_by_hour[period] = current_value
        else:
            if current_value > max_values_by_hour[period]:
                max_values_by_hour[period] = current_value
    
    # 统一写入最终结果
    for period, max_val in max_values_by_hour.items():
        result.write(f"{period},{max_val}\n")

代码说明

  • 用max_values_by_hour字典存储每个小时段的最大值
  • 日期解析格式改为%Y-%m-%d %H,完全匹配原始数据格式
  • 核心逻辑替换为比较当前值与已存储的最大值,保留较大值
  • 使用with语句处理文件,避免手动关闭文件可能出现的错误
  • 最后统一写入结果,避免原代码中重复写入中间过程数据的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:05:26