python - scikit-learn 线性回归索引误差

标签 python pandas scikit-learn linear-regression index-error

我正在开发一个线性回归模型来填充特征Rupeepersqft的空值。当我运行代码时,我收到此错误:

IndexError                                Traceback (most recent call last)
<ipython-input-20-33d4e6d2998e> in <module>()
      1 test_data = data_with_null.iloc[:,:3]
----> 2 Rupeepersqft_predicted['Rupeepersqft'] = pd.DataFrame(linreg.predict(test_data))

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

这是给我错误的代码:

from sklearn.linear_model import LinearRegression
linreg = LinearRegression()

data_with_null = data2[['Price (Lakhs)','Area','Area Type','Rupeepersqft','Condition','Purchase Type','Real Estate Regulation Act']].dropna()
data_without_null =  data_with_null.dropna()

train_data_x = data_without_null.iloc[:,:3]
train_data_y = data_without_null.iloc[:,3]

linreg.fit(train_data_x, train_data_y)

test_data = data_with_null.iloc[:,:3]
Rupeepersqft_predicted['Rupeepersqft'] = pd.DataFrame(linreg.predict(test_data))

data_with_null.Rupeepersqft.fillna(Rupeepersqft_predicted, inplace=True)

数据如下:

Data2

谁能帮我解决这个问题吗?

最佳答案

要将值分配给 Pandas.DataFrame 中的列,您应该使用定位器,即 lociloc (用于类似数组的操作),因此要解决您的问题,请尝试更改

Rupeepersqft_predicted['Rupeepersqft'] = pd.DataFrame(linreg.predict(test_data))

至:

Rupeepersqft_predicted.loc[:, 'Rupeepersqft'] = pd.DataFrame(linreg.predict(test_data))

它将选择所有行(:)和列Rupeepersqft,并分配右侧的任何值。

或使用iloc:

Rupeepersqft_predicted.iloc[:, 1] = pd.DataFrame(linreg.predict(test_data))

将其分配给DataFrame1列的所有行(再次通过:运算符)。

只需确保右侧的值与您尝试分配到的列的长度相同。

有关 Pandas 的更多信息,您可以在 this book 中找到.

干杯

关于python - scikit-learn 线性回归索引误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70024228/

相关文章:

python - 试图找出一种使用 3x3 矩阵比较 9x9 矩阵中数字的方法

python - 使用 Python 和 Matplotlib 将立体图像和深度图转换为 3D 散点图

python - Fastai - 在句子处理器,cache_dir 参数中启动语言模型失败

python - 从包含键和字典项嵌套列表的字典创建 Pandas DataFrame

python - metrics.r2_score 和acccuracy_score 之间有什么区别

python - sklearn.externals 模块说明

python - App Engine/Python/Django 非 JSON 上的身份验证

python - 如何使用离散数据对 Pandas 中的数据进行重新采样?

python - 使用条件语句从 pandas df 列中减去标量给出 ValueError : The truth value of a Series is ambiguous

python - 使用 countvectorizer() 和 tfidfvectorizer() 向量化列表列表