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

Type-coerce indexes when coercion requested at schema level #1139

Merged
merged 1 commit into from
Mar 24, 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
2 changes: 1 addition & 1 deletion pandera/backends/pandas/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ def _try_coercion(coerce_fn, obj):
if schema.coerce:
# coercing at the dataframe-level should apply index coercion
# for both single- and multi-indexes.
index_schema._coerce = True
index_schema.coerce = True
coerced_index = _try_coercion(index_schema.coerce_dtype, obj.index)
if coerced_index is not None:
obj.index = coerced_index
Expand Down
9 changes: 9 additions & 0 deletions tests/core/test_schema_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ def test_index_schema_coerce(dtype):
assert schema.index.dtype.check(validated_index_dtype)


@pytest.mark.parametrize("dtype", [Float, Int, String])
def test_index_schema_coerce_when_coerce_specified_at_schema_level(dtype):
"""Test that index can be type-coerced when coercion requested at schema level"""
schema = DataFrameSchema(index=Index(dtype), coerce=True)
df = pd.DataFrame(index=pd.Index([1, 2, 3, 4], dtype="int64"))
validated_index_dtype = Engine.dtype(schema(df).index.dtype)
assert schema.index.dtype.check(validated_index_dtype)


def test_multi_index_columns() -> None:
"""Tests that multi-index Columns within DataFrames validate correctly."""
schema = DataFrameSchema(
Expand Down