April 21, 2022    Share on: Twitter | Facebook | HackerNews | Reddit

Alow arbitrary types (such as Pandas Dataframe) in Pydantic

Solution 1 - allow arbitrary types

import pandas as pd
from pydantic import BaseModel


class SubModelInput(BaseModel):
    a: pd.DataFrame
    b: pd.DataFrame

    class Config:
        arbitrary_types_allowed = True

Solution 2 - create a pythonic type hint for a pd.Dataframe

import pandas as pd
from pydantic import BaseModel

from typing import TypeVar

PandasDataFrame = TypeVar('pandas.core.frame.DataFrame')


class SubModelInput(BaseModel):
    a: PandasDataFrame
    b: PandasDataFrame

See also

Pandas DataFrame Validation with Pydantic

Hints from: stackoverflow