[Python] Type coercion stops working after an invalid input in `pandera`

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to pandera and really loving it. I encountered a peculiar behavior in one example from the package's side. I am using Python 3.9 and pandera==0.22.1. Copying the snippet for convenience:

    import pandas as pd
    import pandera as pa
    from pandera.typing import Index, DataFrame, Series


    class InputSchema(pa.DataFrameModel):
    year: Series[int] = pa.Field(gt=2000, coerce=True)
    month: Series[int] = pa.Field(ge=1, le=12, coerce=True)
    day: Series[int] = pa.Field(ge=0, le=365, coerce=True)

    class OutputSchema(InputSchema):
    revenue: Series[float]

    @pa.check_types
    def transform(df: DataFrame[InputSchema]) -> DataFrame[OutputSchema]:
    return df.assign(revenue=100.0)


    df = pd.DataFrame({
    "year": ["2001", "2002", "2003"],
    "month": ["3", "6", "12"],
    "day": ["200", "156", "365"],
    })

    transform(df)

    invalid_df = pd.DataFrame({
    "year": ["2001", "2002", "1999"],
    "month": ["3", "6", "12"],
    "day": ["200", "156", "365"],
    })

    try:
    transform(invalid_df)
    except pa.errors.SchemaError as exc:
    print(exc)


    The snippet works as explained in the documentation. However, when I call transform(df) again, I get the following error:

    SchemaError: error in check_types decorator of function 'transform': expected series 'year' to have type int64, got object


    This is surprising because this function call worked without issues in several lines above and all columns were cast into integers. It would sufficient for me to understand if this behavior is expected. As I am new user of this package, maybe I am doing something wrong?

    P.S. I am aware that it is possible to make this repeated call work by overriding Config, but I am just wondering if this behavior is intentional.

    Continue reading...

Compartilhe esta Página