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

如何将Pandas DataFrame中NBA比赛单节时间转换为全场累计时间

将NBA单节时间转换为全场累计时间

实现步骤与代码

  1. 将时间字符串转换为秒数
    先把time列的MM:SS.S格式字符串转换成总秒数,方便数值计算:

    import pandas as pd
    
    # 读取数据
    url = 'https://www.basketball-reference.com/boxscores/pbp/200911060GSW.html'
    dfs = pd.read_html(url)
    df = dfs[0] 
    df.rename(columns={'Unnamed: 2_level_1': 'PM1', 'Unnamed: 4_level_1': 'PM2'}, inplace=True)
    
    # 定义时间转秒数的函数
    def time_to_sec(time_str):
        mins, secs = time_str.split(':')
        return int(mins) * 60 + float(secs)
    
    df['time_sec'] = df['time'].apply(time_to_sec)
    
  2. 计算全场累计时间秒数
    基于你的思路,用向量化方式计算(比循环效率更高):

    # 计算每一行的时间流逝差值:上一行单节时间 - 当前行单节时间
    # 第一行的差值为单节初始时间(720秒)减去第一行的单节时间
    time_diffs = [720 - df['time_sec'].iloc[0]] + list(df['time_sec'].shift(1) - df['time_sec'])[1:]
    
    # 从48分钟(2880秒)开始,减去累计流逝的时间,得到全场累计时间
    df['overall_time_sec'] = 2880 - pd.Series(time_diffs).cumsum()
    
  3. 转换回MM:SS.S格式
    把计算好的秒数转换回原时间格式:

    # 定义秒数转时间字符串的函数
    def sec_to_time(sec):
        mins = int(sec // 60)
        secs = sec % 60
        return f"{mins:02d}:{secs:05.2f}"
    
    df['overall_time'] = df['overall_time_sec'].apply(sec_to_time)
    
    # 移除中间计算列
    df.drop(['time_sec', 'overall_time_sec'], axis=1, inplace=True)
    

说明

  • 转换为秒数是为了避免字符串格式带来的计算障碍,数值计算更直接高效
  • 向量化计算time_diffs和cumsum相比循环遍历,在数据量较大时性能优势明显
  • 最终的overall_time列就是从48:00.0开始递减的全场累计时间,和你预期的计算逻辑完全匹配

内容的提问来源于stack exchange,提问作者nick.s99

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:01:40