在我的 Dataframe 上应用 ColumnTransformer 和 SimpleImputer 后,列的值正在互换

问题描述 投票:0回答:1

我有一个列混合顺序的数据框(xd)。示例 - 分类 1、分类 2、数字 1、分类 3、数字 2、数字 3 等。现在,当我使用列转换器来使用 SimpleImputer 时,输出很奇怪。在输出中,列的值正在互换。例如 - numeric1 列现在具有 categorical1 列的值,categorical3 列具有 numeric2 列的值,依此类推。

每列缺失值: Missing values

Dataframe xd Remaining cols of xd

numerical = xd.select_dtypes(exclude="object").columns
categorical = xd.select_dtypes(include="object").columns

preprocessor = ColumnTransformer(
    transformers=[
        ("impute1", SimpleImputer(strategy="most_frequent"), categorical),
        ("impute2", SimpleImputer(strategy="median"), numerical)
    ],
    remainder="passthrough"
)

X_transformed = preprocessor.fit_transform(xd)
f = pd.DataFrame(X_transformed, columns = xd.columns)
f.head(3)

Output df Output df remaining cols

如果您观察,就会发现列的值正在互换。 KidneyDisease 列具有 Smoker 列的值 酒精饮酒者列具有 BMI 列的值 BMI 列具有睡眠时间列的值 等等。

我还尝试显式指定列:

preprocessor = ColumnTransformer(
    transformers=[
        ("impute1", SimpleImputer(strategy="most_frequent"), ['Sex','GeneralHealth','PhysicalActivities','Stroke','Asthma','SkinCancer','KidneyDisease','Diabetes','DifficultyWalking','Smoker','AgeCategory','AlcoholDrinkers']),
        ("impute2", SimpleImputer(strategy="median"), ['PhysicalHealth', 'MentalHealth', 'SleepHours', 'BMI'])
    ],
    remainder="passthrough"
)
transdorm = preprocessor.fit_transform(xd)

但我仍然面临同样的问题。

这个问题有什么解决办法吗?

pandas machine-learning scikit-learn missing-data
1个回答
0
投票

不要使用原始列创建

f
数据框,因为列已重新排序(首先是“分类”,然后是“数字”,最后是“余数”):
preprocessor.get_feature_names_out()

© www.soinside.com 2019 - 2024. All rights reserved.