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

Bugfix: Ensure defaults are correctly applied #1240

Merged
merged 1 commit into from
Jun 28, 2023
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
11 changes: 10 additions & 1 deletion pandera/backends/pandas/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def validate(

# fill nans with `default` if it's present
if hasattr(schema, "default") and pd.notna(schema.default):
check_obj.fillna(schema.default, inplace=True)
check_obj = self.set_default(check_obj, schema)

if schema.coerce:
try:
Expand Down Expand Up @@ -319,6 +319,15 @@ def run_checks(self, check_obj, schema) -> List[CoreCheckResult]:
)
return check_results

def set_default(self, check_obj, schema):
"""Sets the ``schema.default`` value on the ``check_obj``"""
if is_field(check_obj):
check_obj.fillna(schema.default, inplace=True)
else:
check_obj[schema.name].fillna(schema.default, inplace=True)

return check_obj


class SeriesSchemaBackend(ArraySchemaBackend):
"""Backend for pandas Series objects."""
Expand Down
24 changes: 24 additions & 0 deletions tests/core/test_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -2043,6 +2043,30 @@ def test_default_with_incorrect_dtype_raises_error():
series_schema.validate(series)


def test_default_works_correctly_on_schemas_with_multiple_colummns():
"""Test that each column defaults to the correct value"""

df = pd.DataFrame(
{"x": [1, 2, 3], "y": [None, None, None], "z": [None, None, None]}
).astype("Int64")

schema = DataFrameSchema(
columns={
"x": Column("Int64", nullable=True, default=-999),
"y": Column("Int64", nullable=True, default=123),
"z": Column("Int64", nullable=True, default=1000),
}
)

schema.validate(df, inplace=True)

expected_df = pd.DataFrame(
{"x": [1, 2, 3], "y": [123, 123, 123], "z": [1000, 1000, 1000]}
).astype("Int64")

pd.testing.assert_frame_equal(df, expected_df)


def test_pandas_dataframe_subclass_validation():
"""Test that DataFrame subclasses can be validated by pandera."""

Expand Down