我正在开发一个线性回归模型来填充特征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)
数据如下:
谁能帮我解决这个问题吗?
最佳答案
要将值分配给 Pandas.DataFrame
中的列,您应该使用定位器
,即 loc
和 iloc
(用于类似数组的操作),因此要解决您的问题,请尝试更改
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))
将其分配给DataFrame
第1
列的所有行(再次通过:
运算符)。
只需确保右侧的值与您尝试分配到的列的长度相同。
有关 Pandas
的更多信息,您可以在 this book 中找到.
干杯
关于python - scikit-learn 线性回归索引误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70024228/