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

Handle timestamp and nans in removing multi index failure cases #1516

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
22 changes: 21 additions & 1 deletion pandera/backends/pandas/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from collections import defaultdict
from typing import List, Optional, TypeVar, Union

import numpy as np
import pandas as pd

from pandera.api.base.checks import CheckResult
Expand All @@ -28,6 +29,14 @@
SchemaWarning,
)


_MULTIINDEX_HANDLED_TYPES = {
"Timestamp": pd.Timestamp,
"NaT": pd.NaT,
"nan": np.nan,
}


FieldCheckObj = Union[pd.Series, pd.DataFrame]

T = TypeVar(
Expand Down Expand Up @@ -196,7 +205,18 @@ def drop_invalid_rows(self, check_obj, error_handler: ErrorHandler):
if isinstance(check_obj.index, pd.MultiIndex):
# MultiIndex values are saved on the error as strings so need to be cast back
# to their original types
index_tuples = err.failure_cases["index"].apply(eval)
# fmt: off
index_tuples = (
err.failure_cases["index"]
.astype(str)
.apply(
lambda i: eval(i, _MULTIINDEX_HANDLED_TYPES) # pylint: disable=eval-used
Copy link
Collaborator

Choose a reason for hiding this comment

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

hmm, I didn't realize when this eval snuck into the codebase... are you aware of a more secure way of doing this @rorymcstay ?

Copy link
Collaborator

Choose a reason for hiding this comment

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

looks like I missed the eval change reviewing this change: d43a11b

We don't need to address in this PR, but if you can think of a non-eval approach to this in a separate PR that would be awesome!

)
)
# fmt: on
# type check on a column of index.
if len(index_tuples) == 1 and index_tuples[0] is None:
continue
index_values = pd.MultiIndex.from_tuples(index_tuples)

mask = ~check_obj.index.isin(index_values)
Expand Down
139 changes: 139 additions & 0 deletions tests/core/test_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -2648,3 +2648,142 @@ def test_schema_column_default_handle_nans(
df = pd.DataFrame({"column1": [input_value]})
schema.validate(df, inplace=True)
assert df.iloc[0]["column1"] == default


@pytest.mark.parametrize(
"schema, obj, expected_obj, check_dtype",
[
(
DataFrameSchema(
columns={
"temperature": Column(float, nullable=False),
},
index=MultiIndex(
[
Index(pd.Timestamp, name="timestamp"),
Index(str, name="city"),
]
),
drop_invalid_rows=True,
),
pd.DataFrame(
{
"temperature": [
3.0,
4.0,
5.0,
5.0,
np.nan,
2.0,
],
},
index=pd.MultiIndex.from_tuples(
(
(pd.Timestamp("2022-01-01"), "Paris"),
(pd.Timestamp("2023-01-01"), "Paris"),
(pd.Timestamp("2024-01-01"), "Paris"),
(pd.Timestamp("2022-01-01"), "Oslo"),
(pd.Timestamp("2023-01-01"), "Oslo"),
(pd.Timestamp("2024-01-01"), "Oslo"),
),
names=["timestamp", "city"],
),
),
pd.DataFrame(
{
"temperature": [3.0, 4.0, 5.0, 5.0, 2.0],
},
index=pd.MultiIndex.from_tuples(
(
(pd.Timestamp("2022-01-01"), "Paris"),
(pd.Timestamp("2023-01-01"), "Paris"),
(pd.Timestamp("2024-01-01"), "Paris"),
(pd.Timestamp("2022-01-01"), "Oslo"),
(pd.Timestamp("2024-01-01"), "Oslo"),
),
names=["timestamp", "city"],
),
),
True,
),
(
DataFrameSchema(
columns={
"temperature": Column(float, nullable=False),
},
index=MultiIndex(
[
Index(pd.Timestamp, name="timestamp"),
Index(str, name="city"),
]
),
drop_invalid_rows=True,
),
pd.DataFrame(
{
"temperature": [
3.0,
4.0,
5.0,
-1.0,
np.nan,
-2.0,
4.0,
5.0,
2.0,
],
},
index=pd.MultiIndex.from_tuples(
(
(pd.Timestamp("2022-01-01"), "Paris"),
(pd.Timestamp("2023-01-01"), "Paris"),
(pd.Timestamp("2024-01-01"), "Paris"),
(pd.Timestamp("2022-01-01"), "Oslo"),
(pd.Timestamp("2023-01-01"), "Oslo"),
(pd.Timestamp("2024-01-01"), "Oslo"),
(
pd.Timestamp("2024-01-01", tz="Europe/London"),
"London",
),
(pd.Timestamp(pd.NaT), "Frankfurt"),
(pd.Timestamp("2024-01-01"), 6),
),
names=["timestamp", "city"],
),
),
pd.DataFrame(
{
"temperature": [3.0, 4.0, 5.0, -1.0, -2.0, 4],
},
index=pd.MultiIndex.from_tuples(
(
(pd.Timestamp("2022-01-01"), "Paris"),
(pd.Timestamp("2023-01-01"), "Paris"),
(pd.Timestamp("2024-01-01"), "Paris"),
(pd.Timestamp("2022-01-01"), "Oslo"),
(pd.Timestamp("2024-01-01"), "Oslo"),
(
pd.Timestamp("2024-01-01", tz="Europe/London"),
"London",
),
),
names=["timestamp", "city"],
),
),
False,
),
],
)
def test_drop_invalid_for_multi_index_with_datetime(
schema, obj, expected_obj, check_dtype
):
"""Test drop_invalid_rows works as expected on multi-index dataframes"""
actual_obj = schema.validate(obj, lazy=True)

# the datatype of the index is not casted, In this cases its an object
pd.testing.assert_frame_equal(
actual_obj,
expected_obj,
check_dtype=check_dtype,
check_index_type=check_dtype,
)