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

BTC小时级DataFrame新增日期列并设置为索引的代码指导

BTC小时级数据日期索引转换方案

核心代码实现

假设你的小时级数据DataFrame名为btc_hourly,且索引为datetime类型,按以下步骤操作:

  1. 新增仅含日期的列
    利用pandas的dt访问器从datetime索引中批量提取日期:

    # 提取日期对象格式(如datetime.date(2024,5,20))
    btc_hourly['date'] = btc_hourly.index.dt.date
    
    # 若需要保留datetime格式的日期(如2024-05-20 00:00:00),改用floor方法
    # btc_hourly['date'] = btc_hourly.index.dt.floor('D')
    
  2. 将日期列设为新索引

    btc_hourly = btc_hourly.set_index('date')
    

关键说明

你之前尝试datetime.datetime.date()失败,是因为这是Python标准库针对单个datetime对象的方法,而pandas的DatetimeIndex是批量datetime对象的集合,必须通过.dt访问器调用批量处理方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:02:03