简体   繁体   English

如何在sklearn中修复此自定义转换器?

[英]How to fix this custom transformer in sklearn?

I've written this simple custom transformer that fills na in specific columns with 0. When I fit_transform on my dataset, it does not fill nas in the specified columns. 我已经编写了这个简单的自定义转换器,该转换器在特定的列中用0填充na。当我在数据集上执行fit_transform时,它不会在指定的列中填充nas。 I've failed to see the problem in my code. 我在代码中看不到问题。

class CustomImputer(BaseEstimator, TransformerMixin): 
    def fit(self, X, y=None):
        return self
    def transform(self, X, y=None):
        for col in ('PavedDrive', 'GarageQual', 'GarageFinish', 'FireplaceQu', 'KitchenQual', 'CentralAir', 'HeatingQC', 'BsmtExposure', 'BsmtCond', 'BsmtQual', 'ExterCond', 'ExterQual', 'Street'):
            X[col].fillna(0)
        return X

I expected the returned dataframe to be one where the specified columns have filled nas with 0 however, I get a dataframe with the same null values. 我期望返回的数据帧是其中指定列已用0填充nas的数据帧,但是,我得到的数据帧具有相同的空值。

You never assigned the fillna operation to a new variable. 您从未将fillna操作分配给新变量。 Using 运用

X[col].fillna(0)

does not happen in-place. 不会就地发生。 Instead use: 而是使用:

X.loc[:,col] = X[col].fillna(0)

One liner solution would be 一种班轮解决方案是

cols = ['PavedDrive', 'GarageQual', 'GarageFinish', 'FireplaceQu', 'KitchenQual', 'CentralAir', 'HeatingQC', 'BsmtExposure', 'BsmtCond', 'BsmtQual', 'ExterCond', 'ExterQual', 'Street']

X.loc[:,cols] = X[cols].fillna(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM