“pydantic\validators.py”:未找到< class 'pandas.core.frame. DataFrame'>的验证器

dkqlctbz  于 2023-06-20  发布在  其他
关注(0)|答案(4)|浏览(200)

pydantic没有验证pandas下面的DataFrame。如何处理这一点?

from pydantic.dataclasses import dataclass

@dataclass
class DataFrames:
    dataframe1: pd.DataFrame = None
    dataframe2: pd.DataFrame = None

这将引发以下错误:

File "pydantic\validators.py", line 715, in find_validators

RuntimeError: no validator found for <class 'pandas.core.frame.DataFrame'>, see `arbitrary_types_allowed` in Config
o3imoua4

o3imoua41#

就我个人而言,我输入了错误的类型注解

class Foo(BaseModel):
    bar = Optional[NonNegativeInt]

而不是;

class Foo(BaseModel):
    bar: Optional[NonNegativeInt]

愚蠢的一个ik,但双重检查:)

vof42yt1

vof42yt12#

根据Pydantic Docs,您可以通过多种方式解决问题。
最简单的方法是在模型配置中允许任意类型,但这是与BaseModel打包的功能:再次引用the docs
请记住,pydantic.dataclasses.dataclass是带验证的dataclasses.dataclass的直接替代品,而不是pydantic.BaseModel的替代品
考虑到这一点,下面的代码运行良好:

import pandas as pd
from pydantic import BaseModel

class DataFrames(BaseModel):
    dataframe1: pd.DataFrame = None
    dataframe2: pd.DataFrame = None

    class Config:
        arbitrary_types_allowed = True
0ve6wy6x

0ve6wy6x3#

如果你带着一般性的问题no validator found for <class 'XYZ'>来到这里,你应该检查错过的BaseModel继承:

from pydantic import BaseModel

class MyCustomType: # We forgot inheritance here, should be MyCustomType(BaseModel)
    id: int
    text: str

class MyCustomClass2(BaseModel):
    data: List[MyCustomType]
56lgkhnf

56lgkhnf4#

另一个可能的错误:忘记从BaseModel继承模型,所以:

class Foo():
  bar: str

而不是这样:

class Foo(BaseModel):
  bar: str

相关问题