如何将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
相关产品推荐
相关产品推荐

