My goal is to impute not with sklearn.impute.SimpleImputer
. My goal is to impute with sklearn.preprocessing.FunctionTransformer
. This is because in some cases, it is obvious that we should fill a column based on other column and not with median
or mean
.
The problem is, I can't call get_feature_names_out
What I've tried:
- I tried to use the parameter
feature_names_out
. However, theinput_features
is set to None. - I thought
input_features
is set to None because I did not setvalidate=True
. But, when it throws error.
ValueError: Input X contains NaN.
FunctionTransformer does not accept missing values encoded as NaN natively. For supervised learning, you might want to consider sklearn.ensemble.HistGradientBoostingClassifier and Regressor which accept missing values encoded as NaNs natively. Alternatively, it is possible to preprocess the data, for instance by using an imputer transformer in a pipeline or drop samples with missing values. See https://scikit-learn.org/stable/modules/impute.html You can find a list of all estimators that handle NaN values at the following page: https://scikit-learn.org/stable/modules/impute.html#estimators-that-handle-nan-values
The code
import pandas as pd
import numpy as np
from sklearn.preprocessing import FunctionTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
df = pd.DataFrame(
data={
'PAYMENTS': [np.nan, 100, np.nan],
'MINIMUM_PAYMENTS': [100, 100, 100]
}
)
df
def impute(df):
df['PAYMENTS'].fillna(df['MINIMUM_PAYMENTS'], inplace=True)
return df
def f(self, input_features):
print(input_features)
return input_features
pipe = Pipeline(
steps=[
('imputer', FunctionTransformer(func=impute, feature_names_out=f))
# ('imputer', SimpleImputer(strategy='median'))
]
)
pipe.fit_transform(X=df),
pipe.get_feature_names_out()
validate=False
, define a functiondef f(self): return self.kw_args['features']
. However, I believe this is a hack and there is correct way to do it. I hope someone can point it out. $\endgroup$inplace=True
. That could modify the original data frame that was passed into the pipeline! $\endgroup$inplace=True
. I checked it and it does change the original DataFrame. However, I found a weird behavior, if I useColumnTransformer
on top of 2 pipe, the original DataFrame will not be modified. $\endgroup$ColumnTransformer
has some internal behavior that results in copying the data frame. This site is great for statistics questions, but questions purely about code and programming have usually been redirected to StackOverflow. $\endgroup$