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

Pandas DataFrame使用loc负索引切分数据集触发TypeError如何解决

错误原因

你当前使用的loc索引器是基于DataFrame的索引标签进行切片的,而你的DataFrame索引为DatetimeIndex类型,无法识别-10这类整数位置偏移量,因此触发类型错误。

修复方案

替换为基于整数位置索引的iloc索引器即可,修改后的代码如下:

# 训练集:首行到倒数第11行,仅保留priceUsd列
train = df[['priceUsd']].iloc[:-10]
# 测试集:最后10行,仅保留priceUsd列
test = df[['priceUsd']].iloc[-10:]

如果你需要保留loc的使用场景(比如需要结合时间标签做额外筛选),也可以通过数据集总长度计算切片边界实现:

test_size = 10
train_size = len(df) - test_size
train = df.loc[df.index[:train_size], ['priceUsd']]
test = df.loc[df.index[train_size:], ['priceUsd']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:42:02