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

yfinance下载数据触发KeyError: 'Date'问题求助

解决KeyError: 'Date'问题

我运行代码时出现KeyError: 'Date'错误,我确认自己写的日期列名'Date'和文件里的一致,但还是报错。

我的代码

!pip install yfinance
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import yfinance as yf

# Load your historical data into a DataFrame (make sure to have a 'Date' and 'Close' column)
# You may need to preprocess your data to have the required columns
data = yf.download("^SET.BK", start="2012-01-01", end="2023-07-01")
date_column_name = 'Date'
close_column_name = 'Close'

data[date_column_name] = pd.to_datetime(data[date_column_name])

报错信息

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3801             try:
-> 3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:

4 frames
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'Date'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:
-> 3804                 raise KeyError(key) from err
   3805             except TypeError:
   3806                 # If we have a listlike key, _check_indexing_error will raise

问题原因及解决办法

问题根源

yfinance下载的股票数据默认把日期设置为DataFrame的索引,不是普通的列,所以直接用data['Date']访问会触发KeyError。

解决方法1:把索引转为普通列

如果确实需要将日期作为单独的列使用,执行以下代码:

# 将索引转为名为Date的普通列
data.reset_index(inplace=True)
# 再处理日期格式(yfinance返回的日期已经是datetime类型,这步可省略)
data[date_column_name] = pd.to_datetime(data[date_column_name])

解决方法2:直接使用索引(无需转列)

如果只是需要获取日期信息,不需要单独列,可以直接操作索引:

# 获取日期索引
dates = data.index
# 确认索引类型(yfinance返回的索引已经是datetime64类型,这步可省略)
dates = pd.to_datetime(dates)

验证方法

运行以下代码查看数据结构,确认列和索引的情况:

# 查看前5行数据
print(data.head())
# 查看所有列名
print(data.columns)
# 查看索引信息
print(data.index)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 01:27:33