【问题标题】:Name: price, dtype: int64)' is an invalid key名称:价格,数据类型:int64)' 是无效键
【发布时间】:2020-06-06 13:02:26
【问题描述】:

这是我将其转换为 pandas 对象后的 csv 文件。我正在使用多变量线性回归来创建预测。

    area    bedrooms    age price
0   2600    3.0 20  550000
1   3000    4.0 15  565000
2   3200    NaN 18  610000
3   3600    3.0 30  595000
4   4000    5.0 8   760000


import pandas as pd
import numpy as np
from sklearn import linear_model
import math

df = pd.read_csv("/home/alie/Documents/house.csv",delimiter=",",converters={"price":int})
d = math.floor(df['bedrooms'].mean())
df.bedrooms = df.bedrooms.fillna(d)
reg = linear_model.LinearRegression()
df.columns  = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '')
reg.fit(df[['area', 'bedrooms', 'age'],df.price])

当我做 reg.fit 时,它给了我这个错误,不,关于解决问题的帮助会很有帮助。

    TypeError                                 Traceback (most recent call last)
<ipython-input-51-05a6adc5f668> in <module>
      9 reg = linear_model.LinearRegression()
     10 df.columns  = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '')
---> 11 reg.fit(df[['area', 'bedrooms', 'age'],df.price])

~/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in __getitem__(self, key)
   2925             if self.columns.nlevels > 1:
   2926                 return self._getitem_multilevel(key)
-> 2927             indexer = self.columns.get_loc(key)
   2928             if is_integer(indexer):
   2929                 indexer = [indexer]

~/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2655                                  'backfill or nearest lookups')
   2656             try:
-> 2657                 return self._engine.get_loc(key)
   2658             except KeyError:
   2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

TypeError: '(['area', 'bedrooms', 'age'], 0    550000
1    565000
2    610000
3    595000
4    760000
Name: price, dtype: int64)' is an invalid key

【问题讨论】:

    标签: python-3.x pandas machine-learning scikit-learn


    【解决方案1】:

    无效的键错误类型通常是指尝试访问数据框时的索引不正确。检查第 11 行并确保您正确声明了 df。会不会是:

    reg.fit(df['area', 'bedrooms', 'age'], df.price)
    

    这样 fit 方法得到两个单独的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-13
      • 2021-05-26
      相关资源
      最近更新 更多