Skip to content

Releases

v0.36.0: Add ParsedColumns/Fields and Decisions API

Choose a tag to compare

@cosmicbboy cosmicbboy released this 10 Nov 03:39
2a5d1d6

⭐️ Highlights

In this release, pandera adds support for ParsedFields and ParsedColumns so you can define columns/fields that are derived from other columns/fields. This unlocks a pandera.decisions API that delegates to decision models (like Jev, or a variety of open weights alternatives) to derive columns from a source column/field:

import enum
import pandas as pd
import pandera.pandas as pa
import pandera.decisions as decisions

class Department(str, enum.Enum):
    billing = "billing"
    """Payment, invoices or subscription issues."""
    technical = "technical"
    """Bugs, outages or integration problems."""
    sales = "sales"
    """Pricing, plans or account expansion."""

class Frustration(enum.IntEnum):
    calm = 0
    """Calm, simply stating facts."""
    annoyed = 1
    """Frustrated but civil."""
    angry = 2
    """Very angry, strong language."""

class Triage(pa.DataFrameModel):
    ticket_body: str
    department: Department = pa.ParsedField(
        description="Which team should handle this ticket",
        parser=decisions.Choice(),
    )
    frustration: Frustration = pa.ParsedField(
        description="How frustrated the customer appears",
        parser=decisions.Score(),
    )
    is_urgent: bool = pa.ParsedField(
        description="The message conveys time-sensitivity",
        parser=decisions.Noul(),
    )

    class Config:
        parser_source = "ticket_body"

What's Changed

  • fix(pandas): filter invalid rows using complete check results by @chivector in #2611
  • fix(pandas): add missing columns without an explicit dtype by @chivector in #2609
  • Accept non-string column labels in schema-level unique checks by @feiiiiii5 in #2607
  • docs: add financial transaction reconciliation tutorial by @Numroid in #2605
  • feat(synthesis): pluggable data-synthesis backend primitives by @cosmicbboy in #2578
  • fix(io): preserve datetime comparison bounds in pandas schemas by @chivector in #2613
  • fix: detect pyspark on PYTHONPATH without package metadata for numpy2 patch by @cosmicbboy in #2620
  • docs(polars): clarify LazyFrame validation typing by @Blues-berry in #2623
  • docs(contributing): install uv without pip into the system Python by @thisisshivamtiwari in #2621
  • fix: prevent RCE in tensordict load (GHSA-vpwq-239f-3cf7) by @cosmicbboy in #2627
  • fix(model): don't require optional dtype params in Annotated metadata by @finnhoang05 in #2625
  • docs: generalize the derived-columns spec beyond one decision model by @cosmicbboy in #2527
  • fix(ibis): empty tables vacuously satisfy checks by @inchang-ing in #2629
  • fix(io): restore nested tuple column labels by @bosprimigenious in #2632
  • docs: fix :param names that do not match the signatures by @mmporong in #2619
  • docs: update top banner for DataFusion and fix table dark-mode rendering by @cosmicbboy in #2585
  • feat: map Enum and Literal to categorical data types by @cosmicbboy in #2515
  • fix(polars): make Enum dtypes comparable and hashable by @DG47 in #2634
  • test(pandas): pin signedness in the integer dtype check by @Trenyx in #2630
  • fix(io): preserve single-level MultiIndex schemas by @bosprimigenious in #2636
  • docs: advertise ParsedField/ParsedColumn and the decisions API by @cosmicbboy in #2641
  • perf(polars): read the frame schema once in collect_column_info by @evnchn in #2647

New Contributors

Full Changelog: v0.35.0...v0.36.0

v0.35.0

Choose a tag to compare

@cosmicbboy cosmicbboy released this 25 Oct 02:32
02b375a

⭐️ Highlights

Pandera now supports DataFusion schemas

import pyarrow
from datafusion import SessionContext

import pandera.datafusion as pa

schema = pa.DataFrameSchema(
    {
        "state": pa.Column(str),
        "city": pa.Column(str),
        "price": pa.Column(int, pa.Check.in_range(5, 20)),
    }
)

ctx = SessionContext()
df = ctx.from_arrow(
    pyarrow.table(
        {
            "state": ["FL", "FL", "CA", "CA"],
            "city": ["Orlando", "Miami", "Los Angeles", "San Francisco"],
            "price": [8, 12, 10, 16],
        }
    )
)

schema.validate(df)

And of course the class-based dataframe models as well:

class Schema(pa.DataFrameModel):
    state: str
    city: str
    price: int = pa.Field(in_range={"min_value": 5, "max_value": 20})


Schema.validate(df)

What's Changed

  • ci: fix path-filter quantifier so docs-only PRs skip unit tests by @cosmicbboy in #2545
  • fix: propagate nested Column drop_invalid_rows without mutation by @cosmicbboy in #2551
  • fix(io): read parametrized polars dtypes back from yaml/json by @aminmiral in #2523
  • fix(polars,ibis): ignore nulls in unique_values_eq by @MohammadHijjawi97 in #2538
  • spec: pluggable data synthesis backends (realistic data generation) by @cosmicbboy in #2557
  • docs(spec): apply review fixes to pluggable data synthesis proposal by @cosmicbboy in #2561
  • feat(tensordict): nested keys, element-level check errors, field custom checks, and @check_types integration by @cosmicbboy in #2560
  • fix(io): serialize MultiIndex options so they survive yaml/json/script round trips by @owgreen-dev in #2504
  • feat(datafusion): add datafusion.DataFrame schema validation via the narwhals-datafusion plugin by @s5dsn-eqee in #2540
  • fix(pandas): carry Column default through schema serialization by @feiiiiii5 in #2528
  • fix(decorators): forward validation options to the positional obj_getter selector by @feiiiiii5 in #2499
  • fix(checks): reject conflicting length arguments in Check.str_length by @yang00333 in #2564
  • fix(narwhals): resolve six datafusion xfails in the shared backend by @cosmicbboy in #2562
  • test(polars): reset only polars entries in the shared backend registry by @feiiiiii5 in #2502
  • docs(tensordict): make failure-case example self-contained so docs build passes by @cosmicbboy in #2569
  • fix(polars): coerce to Decimal without a Float64 round trip by @DG47 in #2574
  • fix(pandas): carry report_duplicates and index default through serialization by @aminmiral in #2573
  • docs(contributing): point the Sphinx RST link at the current primer by @Yi-111-a in #2571
  • fix(io): serialize set check statistics such as unique_values_eq by @LuisFigueroaG in #2591
  • fix(tests): suppress large_base_example health check in hypothesis profiles by @cosmicbboy in #2593
  • fix(dask): validate Series indexes by @ska2704 in #2596
  • fix(polars): report a schema error for a non-decimal column by @atharva-mashalkar in #2595
  • fix(engines): resolve parametrized generic Decimal dtypes by @DG47 in #2592
  • fix(pandas): drop columns without deprecated pandas inplace param by @cosmicbboy in #2600
  • fix(xarray): propagate coordinate required metadata by @antoninkriz in #2488
  • fix(io): format dataframe-level checks in to_script by @chuenchen309 in #2418
  • fix(polars): exclude explicit columns from regex alias selectors (#2343) by @capyBearista in #2441
  • docs: advertise DataFusion support in the docs top-level banner by @cosmicbboy in #2604
  • Add explicit stacklevel to warnings and enforce with ruff B028 by @feiiiiii5 in #2500
  • fix(datafusion): fix warning lint and backend test matrix by @Numroid in #2606
  • fix(pandas): don't repeat duplicate-label columns when adding missing columns by @raams95 in #2601
  • docs(api): drop the stray dataframe_schema param from to_json_schema by @VenishPaneliya in #2597
  • fix: only patch numpy 2 aliases for pyspark < 4 (#2134) by @adilKhan72 in #2590
  • ci: don't run the full test matrix for non-CI files under .github/ by @agarg21 in #2589
  • chore: configure Ruff as VS Code formatter by @BALOGUN-DAVID in #2588
  • docs(contributing): fix broken Dataframe schemas examples link by @kun654 in #2587

New Contributors

Full Changelog: v0.34.1...v0.35.0

v0.34.1

Choose a tag to compare

@cosmicbboy cosmicbboy released this 06 Oct 15:15
055ace2

What's Changed

  • Add spec for generic dataframe-agnostic schema API by @cosmicbboy in #2401
  • docs: announce PyTorch TensorDict support in the docs banner by @cosmicbboy in #2544

Full Changelog: v0.34.0...v0.34.1

v0.34.0

Choose a tag to compare

@cosmicbboy cosmicbboy released this 05 Oct 14:34
079c16b

⭐️ Highlights

This release adds TensorDict as a supported data container that can be validated with pandera:

import torch
from tensordict import TensorDict
import pandera.tensordict as pa

schema = pa.TensorDictSchema(
    keys={
        "observation": pa.Tensor(dtype=torch.float32, shape=(None, 10)),
        "action": pa.Tensor(dtype=torch.float32, shape=(None, 5)),
    },
    batch_size=(32,),
)

td = TensorDict(
    {"observation": torch.randn(32, 10), "action": torch.randn(32, 5)},
    batch_size=[32],
)
schema.validate(td)

Or using a class-based model:

class RL(pa.TensorDictModel):
    """Schema for reinforcement learning data."""

    # Use PyTorch dtypes in type annotations
    observation: torch.float32 = pa.Field(shape=(None, 10))
    action: torch.int64 = pa.Field(shape=(None,))
    reward: torch.float32 = pa.Field()

    class Config:
        batch_size = (32,)

# Validate using the model - schema is built automatically
td = TensorDict(
    {"observation": torch.randn(32, 10), "action": torch.randint(0, 4, (32,)), "reward": torch.randn(32)},
    batch_size=[32],
)
RL.validate(td)

What's Changed

  • feat(polars): add support for nested DataFrameModel validation by @Nikhil-jaiswal007 in #2439
  • ci: always run linters, regardless of changed paths by @cosmicbboy in #2462
  • docs: add a "Backward Compatibility" section to AGENTS.md by @Dev-iL in #2461
  • fix(api): raise informative TypeError for non-dataframe validate() input by @cognis-digital in #2421
  • Reject reversed bounds in Check.str_length by @chiruu12 in #2476
  • fix(polars): fail loudly on user-declared parsers instead of skipping them by @feiiiiii5 in #2473
  • fix(polars): honour ignore_na=False when the check output is null by @ebarkhordar in #2471
  • fix(config): coerce a string validation_depth instead of silently disabling gating by @shashvat-singham in #2470
  • docs: clarify parser and check execution order (#2045) by @IshanA2007 in #2466
  • Fix documented default for DataFrameSchema.reset_index drop by @VenishPaneliya in #2465
  • Report integer coercion overflow instead of wrapping silently by @shashvat-singham in #2443
  • fix: correct get_metadata return annotations by @Gagandeep-2003 in #2424
  • Fix implicit Optional on Column dtype in the Ibis backend by @VenishPaneliya in #2474
  • fix(polars): pass parser_output on Category.try_coerce's ParserError so lazy validation reports failure cases instead of crashing by @AmirF194 in #2469
  • fix(polars): do not select absent optional columns when adding missin… by @Moandco in #2460
  • fix(polars): add missing columns with string defaults as literals (#2463) by @Moandco in #2464
  • fix(pandas): match tz-aware datetime dtypes that render identically (#1839) by @cycsmail in #2416
  • docs: derived columns + System One (Jev) parsing proposal by @cosmicbboy in #2508
  • fix(io): keep renamed built-in checks in serialized schemas by @feiiiiii5 in #2501
  • Add PyTorch TensorDict validation backend by @cosmicbboy in #2403
  • fix: pass through unresolved TypeVar annotations in check_types by @sneha4175 in #2513
  • fix(pandas): stop KeyError for column dtypes outside the json-schema types by @feiiiiii5 in #2492
  • fix(pandas): propagate a column's own drop_invalid_rows through DataFrameSchema by @AmirF194 in #2521
  • fix(io): keep groupby and groups when serializing checks by @Rodrigo-Palma in #2490
  • fix(narwhals): handle scalar polars check outputs by @vgvr0 in #2542
  • fix(dtypes): reject negative Decimal scale with the documented error by @feiiiiii5 in #2507

New Contributors

Full Changelog: v0.33.1...v0.34.0

v0.33.1

Choose a tag to compare

@cosmicbboy cosmicbboy released this 01 Sep 15:20
62f55e2

What's Changed

  • docs: announce Pandera CLI and PyArrow support in banner by @cosmicbboy in #2456
  • fix: restore optional-column semantics for bare T | None annotations by @cosmicbboy in #2458
  • Warn when optional columns are missing via on_missing option by @ChrisJr404 in #2447
  • ci: add actionlint workflow and pre-commit hook by @chernojagne in #2436

New Contributors

Full Changelog: v0.33.0...v0.33.1

v0.33.0: Introducing `pandera` CLI, support pyarrow table

Choose a tag to compare

@cosmicbboy cosmicbboy released this 30 Aug 04:16
c37a5b2

What's Changed

  • Report all missing required columns in lazy validation by @vineethsaivs in #2397
  • fix(pandas): report differing categories in dtype mismatch error by @sha-sta in #2391
  • fix(pandas-engine): treat an Enum annotation as a categorical dtype (#2052) by @cycsmail in #2399
  • fix(pandas): run column parsers before dataframe-level coercion by @sha-sta in #2400
  • fix(pandas): treat NA as coercible for masked nullable dtypes by @sha-sta in #2404
  • Fix parenthesized @dataframe_parser() decorator form by @vineethsaivs in #2408
  • fix(polars): avoid concat deprecation in lazy validation by @RedZapdos123 in #2411
  • fix: Repair coerce and parser options for xarray Datasets by @abaarsma in #2413
  • feat(narwhals): support the pandas schema API in the narwhals backend by @cosmicbboy in #2417
  • fix(io): deserialize parametrized Decimal dtypes from yaml/json by @cycsmail in #2434
  • fix(pandas): apply parsers to Index fields and schema components by @cycsmail in #2435
  • feat(pyarrow): add first-class pyarrow.Table schema validation by @sravankumarkunadi in #2427
  • Add a pandera CLI: validate, infer, and generate commands by @cosmicbboy in #2402
  • add backend info to the cli by @cosmicbboy in #2446
  • fix(pandas): respect Optional pydantic fields as nullable in PydanticModel columns (closes #2406) by @feiiiiii5 in #2429
  • doc: Fix "list" type annotation by @VeckoTheGecko in #2440
  • Support itemsize-parameterized numpy dtypes in the pandas engine by @mannemkarthik010 in #2437
  • fix: bind self correctly in check_input when an arg is passed by keyword by @Sanjays2402 in #2428
  • fix(polars): raise minimum polars version to 1.20.0 by @fhoehle in #2412
  • docs: fix duplicated "the" typos in Check and Hypothesis docstrings by @maupatel in #2445
  • Add a backend-neutral FieldType[T] typing contract by @Dev-iL in #2448
  • fix: handle scalar groupby keys in _format_groupby_input by @feiiiiii5 in #2420
  • fix(decorators): support keyword-only / variadic functions in check_input by @feiiiiii5 in #2454
  • ci: only run unit tests for changed areas by @cosmicbboy in #2450
  • fix(docs): make intersphinx fetch resilient to transient failures by @cosmicbboy in #2452
  • fix(docs): scope pyspark JDK24 security-manager opt-in to JDK 24 only by @cosmicbboy in #2451
  • fix: respect pydantic serialization aliases by @mameikagou in #2449

New Contributors

Full Changelog: v0.32.1...v0.33.0

v0.32.1

Choose a tag to compare

@cosmicbboy cosmicbboy released this 29 Jun 16:01
e649b0d

What's Changed

New Contributors

Full Changelog: v0.32.0...v0.32.1

v0.32.0

Choose a tag to compare

@cosmicbboy cosmicbboy released this 19 Jun 00:58
cf13ee4

⭐️ Highlights: Add support for narwhals backend

In this release, we're adding support for a narwhals backend that supports the polars, ibis and pyspark-sql schema APIs. To enable it, install the narwhals extra with the support framework of your choice:

pip install 'pandera[narwhals,polars]'   # Polars
pip install 'pandera[narwhals,ibis]'     # Ibis
pip install 'pandera[narwhals,pyspark]'  # PySpark SQL

Then enable with an environment variable:

export PANDERA_USE_NARWHALS_BACKEND=True

Or configure programmatically:

import pandera.polars as pa 
# import pandera.pyspark as pa  # 👈 for pyspark schemas
# import pandera.ibis as pa  # 👈 for ibis schemas

# CONFIG.use_narwhals_backend is read here — not at import time above
pa.config.set_config(use_narwhals_backend=True)

schema = pa.DataFrameSchema({"name": pa.Column(str)})  # narwhals backends registered
schema.validate(df)

See the docs for more information.

What's Changed

New Contributors

Full Changelog: v0.31.1...v0.32.0

v0.31.1

Choose a tag to compare

@cosmicbboy cosmicbboy released this 15 Apr 03:18
df7cb7d

What's Changed

Full Changelog: v0.31.0...v0.31.1

v0.31.0: Validate Xarray DataArray, Dataset, and DataTree

Choose a tag to compare

@cosmicbboy cosmicbboy released this 14 Apr 01:50

⭐️ Highlights

This is the release for all of you geospatial and multidimensional array-handling folks out there.

xarray support

Pandera now provides full support for xarray 🚀

Write a DatasetSchema with the object-based API

import numpy as np
import xarray as xr
import pandera.xarray as pa

schema = pa.DatasetSchema(
    data_vars={
        "temperature": pa.DataVar(dtype=np.float64, dims=("x", "y")),
        "pressure": pa.DataVar(dtype=np.float64, dims=("x", "y")),
    },
    coords={"x": pa.Coordinate(dtype=np.float64)},
)

ds = xr.Dataset(
    {
        "temperature": (("x", "y"), np.random.rand(3, 4)),
        "pressure": (("x", "y"), np.random.rand(3, 4)),
    },
    coords={"x": np.arange(3, dtype=np.float64)},
)
schema.validate(ds)

Or a DatasetModel with the class-based API:

from pandera.typing.xarray import Coordinate

class Surface(pa.DatasetModel):
    temperature: np.float64 = pa.Field(dims=("x", "y"))
    pressure: np.float64 = pa.Field(dims=("x", "y"))
    x: Coordinate[np.float64]

Surface.validate(ds)

First-class geopandas support

This release also adds first-class GeoDataFrameSchema and GeoDataFrameModel APIs for geopandas: https://pandera.readthedocs.io/en/latest/geopandas.html

What's Changed

New Contributors

Full Changelog: v0.30.1...v0.31.0