ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). How to handle this error?

ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). How to handle this error?

首先在数据集中,我使用均值策略用 imputer class 替换了所有缺失值,但它已将其替换为数据集中的大值,这导致了此错误。这个问题的解决方案是什么,或者我如何将值四舍五入到小数点后两位。由于数据集包含浮点值,因此将它们四舍五入到小数点后 2 位或 3 位对我有用。

代码:

import numpy as np
import pandas as pd
import matplotlib as plt


df=pd.read_csv("C:/Users/asus/Desktop/Life Expectancy Data.csv")
X=df.iloc[:, 4:].values
Y=df.iloc[:,3:4].values

from sklearn.impute import SimpleImputer
imputer=SimpleImputer(missing_values=np.nan,strategy='mean')
imputer.fit(X)
X=imputer.transform(X)

from sklearn.model_selection import train_test_split
X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0)

from sklearn.linear_model import LinearRegression
reg=LinearRegression()
reg.fit(X_train,Y_train)
X_train.replace([np.inf, -np.inf], np.nan, inplace=True)

使用上面的

然后将空值替换为

X_train.fillna(999, inplace=True)

X_train.fillna(X_train.mean(), inplace=True)