Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vectorize apply_replacement #207

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/fklearn/training/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,9 +354,12 @@ def apply_replacements(df: pd.DataFrame,
Default value to replace when original value is not present in the `vec` dict for the feature

"""
column_categorizer = lambda col: df[col].apply(lambda x: (np.nan
if isinstance(x, float) and np.isnan(x)
else vec[col].get(x, replace_unseen)))
def column_categorizer(col: str) -> np.ndarray:
replaced = df[col].map(vec[col])
unseen = df[col].notnull() & replaced.isnull()
replaced[unseen] = replace_unseen
return replaced
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
replaced[unseen] = replace_unseen
return replaced
return replaced.mask(unseen, replace_unseen)


categ_columns = {col: column_categorizer(col) for col in columns}
return df.assign(**categ_columns)

Expand Down
10 changes: 5 additions & 5 deletions tests/training/test_transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ def test_count_categorizer():
expected_output_test = pd.DataFrame(
{
"feat1_num": [2, 20, 200, 2000],
"feat2_cat": [3, 1, 1, 1], # replace unseen vars with constant (1)
"feat2_cat": [3.0, 1.0, 1.0, 1.0], # replace unseen vars with constant (1)
"feat3_cat": [nan, nan, 3, 3],
}
)
Expand Down Expand Up @@ -537,10 +537,10 @@ def test_label_categorizer():
{
"feat1_num": [2, 20, 200, 2000],
"feat2_cat": [
0,
1,
1,
-99,
0.0,
1.0,
1.0,
-99.0,
], # replace unseen vars with constant (1)
"feat3_cat": [nan, nan, 0, 0],
}
Expand Down