我的 Pandas 数据框需要遵守以下 Pandera 架构:
import pandera as pa
from pandera.typing import Series
class schema(pa.SchemaModel):
name: Series[str]
id: Series[str]
但是,在某些数据帧实例中,“id”列将仅包含整数,因此在使用
pd.read_csv()
时将获得“int”数据类型。
例如,我有以下数据框:
当我运行
schema(df).validate()
时,我收到错误:pandera.errors.SchemaError: expected series 'id' to have type str, got int64
但是,在其他情况下,数据框可能看起来像这样:
我想通过允许列成为两种数据类型之一来解决这两种情况。
这是我尝试过的(但它似乎不是正确的语法,因为验证方法不会运行):
import pandera as pa
from pandera.typing import Series
from typing import Union
class schema(pa.SchemaModel):
name: Series[str]
id: Union[Series[str], Series[int]]
Pandera 有什么办法可以做到这一点吗?
尚未实现:参见 https://github.com/unionai-oss/pandera/issues/1152
还有一个拉取请求似乎已经过时了几个月: https://github.com/unionai-oss/pandera/pull/1227