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

如何将DataFrame的datetime索引转换为小时单位的十进制数值?

实现方法

两种单行实现方案,按需选择即可:

  • 直接通过Datetime索引属性计算(无需提前做字符串提取,性能最优):
    df['t_factor'] = df.index.hour + df.index.minute / 60 + df.index.second / 3600
  • 如果你已经生成了%H:%M:%S格式的字符串类型t_factor列,使用如下代码转换:
    df['t_factor'] = pd.to_timedelta(df['t_factor']).dt.total_seconds() / 3600

两种方案均为pandas原生向量化运算,自动完成全列批量处理,无需手动遍历。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:57:03