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: column-level coercion is properly implemented #1612

Merged
merged 1 commit into from
May 5, 2024
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: 8 additions & 3 deletions pandera/backends/polars/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,10 @@ def _coerce_dtype_helper(
error_handler = ErrorHandler(lazy=True)

config_ctx = get_config_context(validation_depth_default=None)

# If validation depth involves validating data, use try_coerce since we
# want to check actual data values. Otherwise, coerce simply detects
# datatype mismatches.
coerce_fn: str = (
"try_coerce"
if config_ctx.validation_depth
Expand All @@ -446,9 +450,10 @@ def _coerce_dtype_helper(
obj = getattr(schema.dtype, coerce_fn)(obj)
else:
for col_schema in schema.columns.values():
obj = getattr(col_schema.dtype, coerce_fn)(
PolarsData(obj, col_schema.selector)
)
if schema.coerce or col_schema.coerce:
obj = getattr(col_schema.dtype, coerce_fn)(
PolarsData(obj, col_schema.selector)
)
except ParserError as exc:
error_handler.collect_error(
validation_type(SchemaErrorReason.DATATYPE_COERCION),
Expand Down
21 changes: 21 additions & 0 deletions tests/polars/test_polars_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import pytest
from hypothesis import given
from hypothesis import strategies as st
from polars.testing import assert_frame_equal
from polars.testing.parametric import column, dataframes

import pandera as pa
Expand Down Expand Up @@ -588,3 +589,23 @@ class Model(DataFrameModel):
{"failure_case": "abc"},
{"failure_case": "String"},
]


def test_dataframe_column_level_coerce():

schema = DataFrameSchema(
{
"a": Column(int, coerce=True),
"b": Column(float, coerce=False),
}
)

df = pl.DataFrame({"a": [1.5, 2.2, 3.1], "b": ["1.0", "2.8", "3"]})
with pytest.raises(
pa.errors.SchemaError,
match="expected column 'b' to have type Float64, got String",
):
schema.validate(df)

schema = schema.update_column("b", coerce=True)
assert_frame_equal(schema.validate(df), df.cast({"a": int, "b": float}))
Loading