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

Python如何按观测数量拆分DatetimeIndex索引的DataFrame

报错原因

切片时传入的索引值是浮点类型,而DatetimeIndex的[]切片不接受浮点数作为位置参数。
你的代码里len(data) * 0.3计算结果是3.0,属于float类型,直接传入切片就会触发如下错误:

TypeError: cannot do slice indexing on DatetimeIndex with these indexers [3.0] of type float

你提到的日期字符串切片属于标签切片逻辑,和按观测行数拆分的位置切片是两套不同的索引逻辑,要按行数拆分不需要依赖索引的日期值。

修复方案

按观测数量(行位置)拆分时,先将拆分阈值转为整数,同时推荐用.iloc显式声明是按位置切片,避免和DatetimeIndex的标签切片逻辑混淆,修改后可正常运行的代码如下:

import pandas as pd

data = {
  'aapl': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 
  'aal' : [33, 33, 33, 32, 31, 30, 34, 29, 27, 26],
}

data = pd.DataFrame(data)
data.index = pd.date_range('2011-01-01', '2011-01-10')

# 计算拆分点时转为整数,int()会直接截断小数部分
n_obs = int(len(data) * 0.3)
# 用iloc做严格的位置切片,和索引类型无关
train, test = data.iloc[:n_obs], data.iloc[n_obs:]
  • 如果需要四舍五入取拆分点,可以把int()替换为round(),例如n_obs = round(len(data) * 0.3)
  • 不要直接用data[:n_obs]的写法:当索引是DatetimeIndex时,这种写法优先走标签匹配逻辑,用.iloc可以明确指定按行号取数,不会出现逻辑歧义。

内容的提问来源于stack exchange,提问作者David L.E

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 03:54:22