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

Create empty dataframe from Pandas DataFrame Model #1880

Merged
merged 5 commits into from
Dec 31, 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
9 changes: 8 additions & 1 deletion pandera/api/dataframe/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
from pandera.engines import PYDANTIC_V2
from pandera.errors import SchemaInitError
from pandera.import_utils import strategy_import_error
from pandera.typing import AnnotationInfo
from pandera.typing import AnnotationInfo, DataFrame
from pandera.typing.common import DataFrameBase
from pandera.utils import docstring_substitution

Expand Down Expand Up @@ -569,6 +569,13 @@ def to_json_schema(cls):
"""Serialize schema metadata into json-schema format."""
raise NotImplementedError

@classmethod
def empty(
cls: Type[TDataFrameModel], *_args
) -> DataFrame[TDataFrameModel]:
"""Create an empty DataFrame instance."""
raise NotImplementedError

if PYDANTIC_V2:

@classmethod
Expand Down
23 changes: 22 additions & 1 deletion pandera/api/pandas/model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Class-based api for pandas models."""

import copy
import sys
from typing import Any, Dict, List, Optional, Tuple, Type, Union

import pandas as pd
Expand All @@ -14,7 +16,18 @@
from pandera.api.parsers import Parser
from pandera.engines.pandas_engine import Engine
from pandera.errors import SchemaInitError
from pandera.typing import get_index_types, get_series_types, AnnotationInfo
from pandera.typing import (
get_index_types,
get_series_types,
AnnotationInfo,
DataFrame,
)

# if python version is < 3.11, import Self from typing_extensions
if sys.version_info < (3, 11):
from typing_extensions import Self
else:
from typing import Self

SchemaIndex = Union[Index, MultiIndex]

Expand Down Expand Up @@ -191,6 +204,14 @@
},
}

@classmethod
def empty(cls: Type[Self], *_args) -> DataFrame[Self]:
"""Create an empty DataFrame with the schema of this model."""
schema = copy.deepcopy(cls.to_schema())
schema.coerce = True
empty_df = schema.coerce_dtype(pd.DataFrame(columns=[*schema.columns]))
return DataFrame[Self](empty_df)

Check warning on line 213 in pandera/api/pandas/model.py

View check run for this annotation

Codecov / codecov/patch

pandera/api/pandas/model.py#L210-L213

Added lines #L210 - L213 were not covered by tests


def _build_schema_index(
indices: List[Index], **multiindex_kwargs: Any
Expand Down
14 changes: 14 additions & 0 deletions tests/core/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1542,3 +1542,17 @@ class Schema(pa.DataFrameModel):
assert Schema.validate(df).equals( # type: ignore [attr-defined]
pd.DataFrame({"a": [1.0], "b": [1], "c": ["1"]})
)


def test_empty() -> None:
"""Test to generate an empty DataFrameModel."""

class Schema(pa.DataFrameModel):
a: Series[pa.Float]
b: Series[pa.Int]
c: Series[pa.String]
d: Series[pa.DateTime]

df = Schema.empty()
assert df.empty
assert Schema.validate(df).empty # type: ignore [attr-defined]
Loading