我仍在学习人工智能并尝试创建线性回归算法模型,但是在尝试弹出列时不断收到KeyError。



我从tim的一门python技术课程中学习,我用他的代码编写了一个基本的线性回归算法,并试图制作我自己的小数据表来尝试,每当我导入数据表时,它都会显示以下错误:

KeyError: 'xvalue'
The above exception was the direct cause of the following exception:
KeyError                                  Traceback (most recent call last)
4 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2898                 return self._engine.get_loc(casted_key)
2899             except KeyError as err:
-> 2900                 raise KeyError(key) from err
2901 
2902         if tolerance is not None:
KeyError: 'xvalue'

我的代码如下:

from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import clear_output
from six.moves import urllib
import tensorflow.compat.v2.feature_column as fc
import tensorflow as tf
# Load dataset.
train = "https://docs.google.com/spreadsheets/d/1qQfNL2ePWVsOiqSNgJu_ZwmI9KFwFTrtdb1boqIKFZQ/edit?usp=sharing"
eval = "https://docs.google.com/spreadsheets/d/1Ip1Key9NYx3boTUFkPUOzEWdtUBMeGJJEY3MbSpVkUo/edit?usp=sharing"
dftrain = pd.read_csv(train, sep='t,s*') # training data
dfeval = pd.read_csv(eval, sep='t,s*') # testing data
y_train = dftrain.pop('xvalue')
y_eval = dfeval.pop('xvalue')

我正在使用谷歌python笔记本来编写这个代码,如果有任何帮助,我们将不胜感激!

如果您想导出Google Sheets电子表格的内容,可以使用此答案中的建议。

在您的情况下,您使用的是Pandas,因此不需要使用requests包。

所以你可以定义这个函数:

def get_docs_url(doc_id):
url = f"https://docs.google.com/spreadsheet/ccc?key={doc_id}&output=csv"
return url

并像这样使用:

train = get_docs_url('1qQfNL2ePWVsOiqSNgJu_ZwmI9KFwFTrtdb1boqIKFZQ')
dftrain = pd.read_csv(train) # training data

PS:我删除了sep='t,s*'部分,因为它不需要解析CSV文件。

PPS:测试数据集与列车数据集具有不同的列名。我需要添加dfeval = dfeval.rename(columns={'X': 'xvalue', 'Y': 'yvalue'})才能使其工作。

最新更新