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

Pandas中groupby().sum()对时间列拼接而非求和的问题求助

问题原因

你的appointedTime列存储的是字符串类型(比如"00:10"),Pandas的sum()方法对字符串执行的是拼接操作,而非数值求和,这就是结果中时间字符串被连在一起的原因。

解决方案

要实现时间求和,需先把字符串格式的时长转换成Pandas可识别的timedelta(时间增量)类型,再进行分组求和。具体步骤如下:

1. 解析字符串时长为timedelta

使用pd.to_timedelta()函数,将HH:MM格式的字符串转换为timedelta类型,该函数能自动识别小时、分钟格式的时长。

2. 分组求和

转换类型后,groupby().sum()就能正确计算时长总和。注意Pandas新版本默认numeric_only=True,需显式设置numeric_only=False以支持timedelta类型的求和。

3. 可选:转换为友好的字符串格式

如果需要把求和后的timedelta转回HH:MM格式的字符串,可以自定义转换函数。

修改后的代码
def get_report(cookie):
    from datetime import datetime, timedelta
    import requests
    import json
    import pandas as pd

    today = datetime.today().strftime("%Y-%m-%d")  # 减timedelta(days=0)可省略
    link_report = f'https://atendimento.sistemainfo.com.br/Report/WorkTimeResultToJsonAsync?StartDate={today}&EndDate={today}&TicketType=&Agents%5B0%5D.Id=16086163&Agents%5B0%5D.ToDelete=False&Agents%5B1%5D.Id=40721217&Agents%5B1%5D.ToDelete=False&Agents%5B2%5D.Id=16810784&Agents%5B2%5D.ToDelete=False&Agents%5B3%5D.Id=19891551&Agents%5B3%5D.ToDelete=False&Agents%5B4%5D.Id=23034581&Agents%5B4%5D.ToDelete=False&Agents%5B5%5D.Id=21459575&Agents%5B5%5D.ToDelete=False&Agents%5B6%5D.Id=28407059&Agents%5B6%5D.ToDelete=False&Agents%5B7%5D.Id=34454555&Agents%5B7%5D.ToDelete=False&Agents%5B8%5D.Id=28492909&Agents%5B8%5D.ToDelete=False&_=1666122828849'
    request_report = requests.get(link_report, cookies=cookie)

    reports = json.loads(request_report.content)['list']

    # 直接用返回数据构建DataFrame,无需手动遍历列表
    df = pd.DataFrame(reports, columns=['agent', 'appointedTime'])

    # 核心步骤:将字符串时长转为timedelta类型
    df['appointedTime'] = pd.to_timedelta(df['appointedTime'])

    # 分组求和,支持timedelta类型
    df2 = df.groupby('agent').sum(numeric_only=False)

    # 可选:将timedelta转为HH:MM格式的字符串
    def format_timedelta(td):
        total_seconds = td.total_seconds()
        hours = int(total_seconds // 3600)
        minutes = int((total_seconds % 3600) // 60)
        return f"{hours:02d}:{minutes:02d}"

    df2['appointedTime'] = df2['appointedTime'].apply(format_timedelta)

    print(df2)

get_report(get_cookies())
关键说明
  • 移除了手动遍历列表的冗余代码,直接用pd.DataFrame()构建数据框更简洁高效。
  • pd.to_timedelta()自动处理HH:MM格式,无需手动拆分小时和分钟。
  • numeric_only=False确保Pandas不会忽略timedelta类型的求和操作。
  • 自定义的format_timedelta函数将总时长转换为易读的HH:MM格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:50:33