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

[data/preprocessors] do not fail transform_batch on missing column #48137

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 10 additions & 2 deletions python/ray/data/preprocessors/imputer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@

@PublicAPI(stability="alpha")
class SimpleImputer(Preprocessor):
"""Replace missing values with imputed values.
"""Replace missing values with imputed values. If the column is missing from a
batch, it will be filled with the imputed value.

Examples:
>>> import pandas as pd
Expand Down Expand Up @@ -131,7 +132,14 @@ def _transform_pandas(self, df: pd.DataFrame):
if is_categorical_dtype(df.dtypes[column]):
df[column] = df[column].cat.add_categories(value)

df = df.fillna(new_values)
for column_name in new_values:
Copy link
Contributor

Choose a reason for hiding this comment

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

can you add this behavior to the docstring as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done!

if column_name not in df.columns:
# Create the column with the fill_value if it doesn't exist
df[column_name] = new_values[column_name]
else:
# Fill NaN (empty) values in the existing column with the fill_value
df[column_name].fillna(new_values[column_name], inplace=True)

return df

def __repr__(self):
Expand Down
12 changes: 12 additions & 0 deletions python/ray/data/tests/preprocessors/test_imputer.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ def test_simple_imputer():

assert pred_out_df.equals(pred_expected_df)

# with missing column
pred_in_df = pd.DataFrame.from_dict({"A": pred_col_a, "B": pred_col_b})
pred_out_df = imputer.transform_batch(pred_in_df)
pred_expected_df = pd.DataFrame.from_dict(
{
"A": pred_processed_col_a,
"B": pred_processed_col_b,
"C": pred_processed_col_c,
}
)
assert pred_out_df.equals(pred_expected_df)

# Test "most_frequent" strategy.
most_frequent_col_a = [1, 2, 2, None, None, None]
most_frequent_col_b = [None, "c", "c", "b", "b", "a"]
Expand Down