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

如何将Jupyter Notebook中数据集的时长列转换为小时和分钟?

字符串时长转可视化可用的数值格式

情况1:时长格式为1d2h30m、45s这类带单位的字符串

先导入需要的库:

import pandas as pd
import re

写一个转换函数,把时长转成总秒数(也可以按需转成分钟/小时):

def duration_to_secs(duration_str):
    # 匹配数字+单位的正则
    parts = re.findall(r'(\d+)([dhms])', duration_str)
    total = 0
    for num, unit in parts:
        num = int(num)
        if unit == 'd':
            total += num * 86400
        elif unit == 'h':
            total += num * 3600
        elif unit == 'm':
            total += num * 60
        elif unit == 's':
            total += num
    return total

把函数应用到你的数据列上:

# 假设数据集是df,时长列名为'duration'
df['duration_secs'] = df['duration'].apply(duration_to_secs)

情况2:时长格式为01:30:00(时分秒)或1:30(分秒)

这种格式可以直接用pandas的内置方法处理:

df['duration_secs'] = pd.to_timedelta(df['duration']).dt.total_seconds()

转成数值(比如总秒数)后,就可以直接用matplotlib、seaborn等库做可视化了——比如画时长分布的直方图、箱线图,或者和其他列做关联分析图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:50:28