I'm not really used to working with pipelines, so I'm wondering how can I use custom functions and pipelines.
Situation: I want to fill some missing values with the mean but using groups based on other feature. That's why I'm using this custom function:
def replaceNullFromGroup(From, To, variable, by):
# 1. Create aggregation from train dataset
From_grp = From.groupby(by)[variable].median().reset_index()
# 2. Merge dataframes
To_merged = To.merge(From_grp, on=by, suffixes=['_test', '_train'], how = "left")
# 3. Create dictionaries
to_cols = [col for col in To_merged.columns if 'test' in col]
from_cols = [col for col in To_merged.columns if 'train' in col]
dict_cols =dict(zip(to_cols, from_cols))
# 4. Replace null values
for to_col, from_col in dict_cols.items():
To_merged[to_col] = np.where(To_merged[to_col].isnull(),
To_merged[from_col],
To_merged[to_col])
# 5. Clean up dataframe
To_merged.drop(from_col, axis=1, inplace=True)
To_merged.columns = To_merged.columns.str.replace('_test', '')
return To_merged
Variables meaning:
- From: Dataframe where I'm taking the information (Train dataset)
- To: Dataframe where I will fill the missing values (Train and test dataset)
- variable: variable with missing values
- by: Variables I'm using to make groups
Can I use this function in a pipeline so I can use cross validation avoiding data leakage?
Thank you very much