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

如何在Pandas中将天数转换为小时数

在Pandas中将天数转换为小时数的实现方法

需求说明

需要将DataFrame中expiration列的天数格式(如1d、2d)转换为对应的小时数格式(24h、48h),小时格式(如2h)保持不变。

输入示例

coupon expiration
0       Restaurant         1d
1          College         2d
2    Coffee House         2h

实现代码

最简洁的方式是使用Pandas的字符串替换结合正则表达式,一步完成转换:

import pandas as pd

# 构造示例数据
data = {
    'coupon': ['Restaurant', 'College', 'Coffee House'],
    'expiration': ['1d', '2d', '2h']
}
df = pd.DataFrame(data)

# 执行转换:将Xd格式替换为X*24h
df['expiration'] = df['expiration'].str.replace(r'(\d+)d', lambda m: f"{int(m.group(1))*24}h")

输出结果

coupon expiration
0       Restaurant        24h
1          College        48h
2    Coffee House         2h

代码解释

  • str.replace(r'(\d+)d', ...):正则表达式(\d+)d匹配所有以d结尾的天数格式,其中(\d+)捕获数字部分;
  • lambda m: f"{int(m.group(1))*24}h":将捕获的数字转为整数后乘以24,再拼接成h结尾的字符串,实现天数到小时数的转换;
  • 原本的小时格式(如2h)不会被正则匹配,因此保持原样。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:01:25