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

如何拆分DataFrame的time_taken列?遇ValueError: invalid unit abbreviation: hm

解决DataFrame中「02h 10m」格式列拆分小时/分钟的问题

错误原因

你遇到的ValueError: invalid unit abbreviation: hm是因为pd.to_timedelta无法直接解析带空格的「Xh Ym」格式字符串——它默认支持无空格的缩写形式(如'2h10m')或标准时间格式(如'02:10:00'),空格的存在导致它无法正确识别时间单位。

解决方案

以下是三种可行的实现方式,按需选择:

方法1:预处理字符串后用pd.to_timedelta

先移除原字符串中的空格,转换成pd.to_timedelta支持的格式,再提取小时和分钟:

# 清理格式:去掉空格
df3['time_taken_clean'] = df3['time_taken'].str.replace(' ', '')
# 转换为时间增量对象
t = pd.to_timedelta(df3['time_taken_clean'])
# 提取小时和分钟
df3['hours'] = t.dt.components['hours']
df3['minutes'] = t.dt.components['minutes']

方法2:正则表达式直接提取数字

直接匹配字符串中的数字部分,跳过时间转换步骤,效率更高:

# 提取小时数字并转为整数
df3['hours'] = df3['time_taken'].str.extract(r'(\d+)h').astype(int)
# 提取分钟数字并转为整数
df3['minutes'] = df3['time_taken'].str.extract(r'(\d+)m').astype(int)

方法3:拆分字符串后单独处理

将字符串按空格拆分为小时和分钟两部分,再分别移除单位符号并转换:

# 按空格拆分字符串,生成两列
split_cols = df3['time_taken'].str.split(' ', expand=True)
# 提取小时
df3['hours'] = split_cols[0].str.replace('h', '').astype(int)
# 提取分钟
df3['minutes'] = split_cols[1].str.replace('m', '').astype(int)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:10:16