【问题标题】:Why is SimpleImputer returning categorical data?为什么 SimpleImputer 返回分类数据?
【发布时间】:2021-11-25 02:08:02
【问题描述】:
我使用fillna 将数值输入数据框,SimpleImputer 用于分类列。问题是当我运行以下代码时,我注意到我的所有特征都是分类的。
X = X.fillna(X.mean())
X_test = X_test.fillna(X_test.mean())
object_imputer = SimpleImputer(strategy="most_frequent")
X_temp = pd.DataFrame(object_imputer.fit_transform(X))
X_temp_test = pd.DataFrame(object_imputer.fit_transform(X_test))
X_temp.columns = X.columns
X_temp_test.columns = X_test.columns
X, X_test = X_temp, X_temp_test
fillna 工作正常,但导致我出现问题的是 SimpleImputer。
您能告诉我问题是什么以及如何解决吗?提前致谢
【问题讨论】:
标签:
python
pandas
scikit-learn
imputation
【解决方案1】:
在我说任何其他内容之前,请注意您正在将您的估算器安装在 X 上,然后再安装在 X_test 上。你不应该这样做。相反,您应该始终将您的 imputer 拟合到训练数据上,然后使用该实例来转换两个数据集(训练和测试数据)。
话虽如此,您的问题是您正在拟合和转换所有列。结果,imputer 将所有列转换为类型object。
我相信这会解决你的问题:
# Impute NaNs of numeric columns
X = X.fillna(X.mean())
X_test = X_test.fillna(X_test.mean())
# Subset of categorical columns
cat = ['Loan_ID','Gender','Married','Dependents','Education','Self_Employed',
'Credit_History','Loan_Status']
# Fit Imputer on traing data and ONLY on categorical columns
object_imputer = SimpleImputer(strategy='most_frequent').fit(X[cat])
# Transform ONLY categorical columns
X[cat] = object_imputer.transform(X[cat])
X_test[cat] = object_imputer.transform(X_test[cat])
如您所见,所有列现在都具有正确的数据类型。
X.dtypes
Loan_ID object
Gender object
Married object
Dependents object
Education object
Self_Employed object
ApplicantIncome int64
CoapplicantIncome float64
LoanAmount float64
Loan_Amount_Term float64
Credit_History float64
Property_Area object
Loan_Status object
dtype: object