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

fix: properly coerce dtypes for columns with regex=True #1602

Merged
merged 5 commits into from
May 6, 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
8 changes: 6 additions & 2 deletions pandera/backends/pandas/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,9 +633,13 @@ def _try_coercion(coerce_fn, obj):
matched_columns = pd.Index([])

for matched_colname in matched_columns:
if col_schema.coerce or schema.coerce:
if (
col_schema.coerce or schema.coerce
) and schema.dtype is None:
_col_schema = copy.deepcopy(col_schema)
_col_schema.coerce = True
obj[matched_colname] = _try_coercion(
col_schema.coerce_dtype, obj[matched_colname]
_col_schema.coerce_dtype, obj[matched_colname]
)
elif (
(col_schema.coerce or schema.coerce)
Expand Down
27 changes: 27 additions & 0 deletions tests/core/test_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -2421,6 +2421,33 @@ class Config:
MySchema.validate(actual_obj, lazy=False)


def test_schema_coerce() -> None:
"""Test that setting coerce=True for a DataFrameSchema is sufficient to coerce a column."""

schema = DataFrameSchema(
columns={"col": Column(dtype=bool)},
coerce=True,
)

df = pd.DataFrame({"col": [1, 0]})

assert isinstance(schema.validate(df), pd.DataFrame)


def test_schema_coerce_with_regex() -> None:
"""Test that setting coerce=True for a DataFrameSchema is sufficient to coerce a column in the case
where the column has regex=True."""

schema_with_regex = DataFrameSchema(
columns={"col": Column(dtype=bool, regex=True)},
coerce=True,
)

df = pd.DataFrame({"col": [1, 0]})

assert isinstance(schema_with_regex.validate(df), pd.DataFrame)


@pytest.mark.parametrize(
"schema, obj, expected_obj",
[
Expand Down
Loading