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

机器学习股票价格预测报错:'DataFrame'无'symbol'属性的排查与修复

解决DataFrame无'symbol'属性的错误(股票价格预测模型)

错误原因

  • 你加载的GOOG.csv文件中不存在名为symbol的列,所以调用df.symbol会触发属性不存在的错误。
  • 另外,你加载的是单独的谷歌股票数据文件,本身就只包含GOOG的股价数据,完全不需要通过symbol列进行筛选。

修复方案

方案1(针对单股票CSV)

直接删除报错的那一行代码:

df = df[df.symbol == "GOOG"]  # 删掉这行

单个股票的CSV数据不需要额外筛选,加载后直接使用即可。

方案2(针对多股票合并CSV)

如果你的CSV是包含多支股票的数据集(比如有symbol列区分不同个股),请:

  • 打开CSV文件检查列名,确认是否存在symbol列,注意大小写(比如可能是Symbol而非全小写的symbol)
  • 如果列名是大写,修改代码为:
    df = df[df.Symbol == "GOOG"]
    

修正后的完整代码

import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

def prepare_data(df, forecast_col, forecast_out, test_size):
    label = df[forecast_col].shift(-forecast_out)  # 创建label列,最后5行为NaN
    X = np.array(df[[forecast_col]])  # 创建特征数组(修正了多余空格)
    X = preprocessing.scale(X)  # 标准化特征
    X_lately = X[-forecast_out:]  # 准备用于预测的最后n行数据
    X = X[:-forecast_out]  # 用于训练测试的特征数据
    label.dropna(inplace=True)  # 移除NaN值
    y = np.array(label)  # 赋值标签y
    # 拆分训练集和测试集
    X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=test_size, random_state=0)

    return [X_train, X_test, Y_train, Y_test, X_lately]

df = pd.read_csv("GOOG.csv")
# 移除了报错的筛选行
forecast_col = "close"
forecast_out = 5
test_size = 0.2

X_train, X_test, Y_train, Y_test, X_lately = prepare_data(df, forecast_col, forecast_out, test_size)
learner = LinearRegression()
learner.fit(X_train, Y_train)
score = learner.score(X_test, Y_test)  # 评估模型
forecast = learner.predict(X_lately)  # 生成预测结果

response = {}
response['test_score'] = score
response['forecast_set'] = forecast

print(response)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:31:21