如何将Pandas数据框中的时长字符串转换为小时数值?
将Pandas文本时长转换为小时数值的方法
这里提供两种实用的实现方式,根据你的需求选择即可:
方法一:利用Pandas内置时间差解析函数(简洁高效)
Pandas的pd.to_timedelta()可以直接识别你给出的两种时长格式,之后将总秒数转换为小时即可:
import pandas as pd # 示例数据 data = {'Duration': ['16h:48m:31s', '0h:02m:49s', '1d 3h:57m:27s']} df = pd.DataFrame(data) # 转换为小时数值 df['Duration_hours'] = pd.to_timedelta(df['Duration']).dt.total_seconds() / 3600
处理后的数据框结果:
Duration Duration_hours 0 16h:48m:31s 16.808611 1 0h:02m:49s 0.046944 2 1d 3h:57m:27s 27.957500
方法二:自定义正则提取函数(灵活可控)
如果需要应对更多特殊格式或自定义计算逻辑,可以用正则表达式提取各时间单位的数值,再手动计算总小时数:
import pandas as pd import re def convert_duration(dur_str): # 匹配各时间单位的数值,无匹配则返回0 day_match = re.findall(r'(\d+)d', dur_str) hour_match = re.findall(r'(\d+)h', dur_str) min_match = re.findall(r'(\d+)m', dur_str) sec_match = re.findall(r'(\d+)s', dur_str) days = int(day_match[0]) if day_match else 0 hours = int(hour_match[0]) if hour_match else 0 mins = int(min_match[0]) if min_match else 0 secs = int(sec_match[0]) if sec_match else 0 # 计算总小时数 return days * 24 + hours + mins / 60 + secs / 3600 # 应用转换函数 df['Duration_hours'] = df['Duration'].apply(convert_duration)
两种方法结果一致:第一种适合常规场景,代码量少;第二种适合需要定制逻辑的特殊情况。
内容的提问来源于stack exchange,提问作者Solijoli
相关产品推荐
相关产品推荐

