模式推断与持久化

版本0.4.0中的新功能

对于简单的用例,手动编写架构定义是相当简单的,使用 pandera。然而,对于具有多种数据类型的多列数据框,这可能变得繁琐。

从数据推断模式

为了帮助您处理这些情况,infer_schema() 函数使您能够快速从 pandas 数据框或系列推断出草稿模式。下面是一个简单的示例:

import pandas as pd
import pandera as pa

df = pd.DataFrame({
    "column1": [5, 10, 20],
    "column2": ["a", "b", "c"],
    "column3": pd.to_datetime(["2010", "2011", "2012"]),
})
schema = pa.infer_schema(df)
print(schema)
<Schema DataFrameSchema(
    columns={
        'column1': <Schema Column(name=column1, type=DataType(int64))>
        'column2': <Schema Column(name=column2, type=DataType(object))>
        'column3': <Schema Column(name=column3, type=DataType(datetime64[ns]))>
    },
    checks=[],
    parsers=[],
    coerce=True,
    dtype=None,
    index=<Schema Index(name=None, type=DataType(int64))>,
    strict=False,
    name=None,
    ordered=False,
    unique_column_names=False,
    metadata=None, 
    add_missing_columns=False
)>

这些推断出的模式是 粗略草稿,在未修改的情况下不应用于验证。您可以修改推断的模式,以获得您满意的模式定义。

对于 DataFrameSchema 对象,以下方法创建架构的修改副本:

  • add_columns()

  • remove_columns()

  • update_column()

对于 SeriesSchema 对象:

  • set_checks()

下面的部分描述了持久化和修改推断模式的两个工作流程。

持久化模式

模式持久性功能需要安装带有 io 扩展的 pandera。有关更多详细信息,请参见 安装 说明。

有两种持久化模式的方法,一种是推断的,另一种是其他方式。

写入Python脚本

您还可以将您的模式写入一个 python 脚本,使用 to_script()

# supply a file-like object, Path, or str to write to a file. If not
# specified, to_script will output the code as a string.
schema_script = schema.to_script()
print(schema_script)
from pandas import Timestamp
from pandera import DataFrameSchema, Column, Check, Index, MultiIndex

schema = DataFrameSchema(
    columns={
        "column1": Column(
            dtype="int64",
            checks=[
                Check.greater_than_or_equal_to(
                    min_value=5.0, raise_warning=False, ignore_na=True
                ),
                Check.less_than_or_equal_to(
                    max_value=20.0, raise_warning=False, ignore_na=True
                ),
            ],
            nullable=False,
            unique=False,
            coerce=False,
            required=True,
            regex=False,
            description=None,
            title=None,
        ),
        "column2": Column(
            dtype="object",
            checks=None,
            nullable=False,
            unique=False,
            coerce=False,
            required=True,
            regex=False,
            description=None,
            title=None,
        ),
        "column3": Column(
            dtype="datetime64[ns]",
            checks=[
                Check.greater_than_or_equal_to(
                    min_value=Timestamp("2010-01-01 00:00:00"),
                    raise_warning=False,
                    ignore_na=True,
                ),
                Check.less_than_or_equal_to(
                    max_value=Timestamp("2012-01-01 00:00:00"),
                    raise_warning=False,
                    ignore_na=True,
                ),
            ],
            nullable=False,
            unique=False,
            coerce=False,
            required=True,
            regex=False,
            description=None,
            title=None,
        ),
    },
    checks=None,
    index=Index(
        dtype="int64",
        checks=[
            Check.greater_than_or_equal_to(
                min_value=0.0, raise_warning=False, ignore_na=True
            ),
            Check.less_than_or_equal_to(
                max_value=2.0, raise_warning=False, ignore_na=True
            ),
        ],
        nullable=False,
        coerce=False,
        name=None,
        description=None,
        title=None,
    ),
    dtype=None,
    coerce=True,
    strict=False,
    name=None,
    ordered=False,
    unique=None,
    report_duplicates="all",
    unique_column_names=False,
    add_missing_columns=False,
    title=None,
    description=None,
)

作为一个python脚本,您可以遍历推断出的模式,并在对模式定义满意后用它来验证数据。

写入YAML

您也可以使用 to_yaml() 将模式对象写入 yaml 文件,然后可以使用 from_yaml() 将其读入内存。 to_yaml()from_yaml() 是此功能的便捷方法。

# supply a file-like object, Path, or str to write to a file. If not
# specified, to_yaml will output a yaml string.
yaml_schema = schema.to_yaml()
print(yaml_schema)
schema_type: dataframe
version: 0.0.0+dev0
columns:
  column1:
    title: null
    description: null
    dtype: int64
    nullable: false
    checks:
      greater_than_or_equal_to:
        value: 5.0
        options:
          raise_warning: false
          ignore_na: true
      less_than_or_equal_to:
        value: 20.0
        options:
          raise_warning: false
          ignore_na: true
    unique: false
    coerce: false
    required: true
    regex: false
  column2:
    title: null
    description: null
    dtype: object
    nullable: false
    checks: null
    unique: false
    coerce: false
    required: true
    regex: false
  column3:
    title: null
    description: null
    dtype: datetime64[ns]
    nullable: false
    checks:
      greater_than_or_equal_to:
        value: '2010-01-01 00:00:00'
        options:
          raise_warning: false
          ignore_na: true
      less_than_or_equal_to:
        value: '2012-01-01 00:00:00'
        options:
          raise_warning: false
          ignore_na: true
    unique: false
    coerce: false
    required: true
    regex: false
checks: null
index:
- title: null
  description: null
  dtype: int64
  nullable: false
  checks:
    greater_than_or_equal_to:
      value: 0.0
      options:
        raise_warning: false
        ignore_na: true
    less_than_or_equal_to:
      value: 2.0
      options:
        raise_warning: false
        ignore_na: true
  name: null
  unique: false
  coerce: false
dtype: null
coerce: true
strict: false
name: null
ordered: false
unique: null
report_duplicates: all
unique_column_names: false
add_missing_columns: false
title: null
description: null

您可以编辑这个yaml文件以修改架构。例如,您可以在column键下指定新的列名,并且相应的值映射到Column类中的关键字参数。

注意

目前,仅支持内置的 Check 方法在 checks 键下。

写入 JSON

最后,您还可以使用 to_json() 将模式对象写入 json 文件,然后可以使用 from_json() 将其读入内存。to_json()from_json() 是此功能的便捷方法。

# supply a file-like object, Path, or str to write to a file. If not
# specified, to_yaml will output a yaml string.
json_schema = schema.to_json(indent=4)
print(json_schema)
{
    "schema_type": "dataframe",
    "version": "0.0.0+dev0",
    "columns": {
        "column1": {
            "title": null,
            "description": null,
            "dtype": "int64",
            "nullable": false,
            "checks": {
                "greater_than_or_equal_to": {
                    "value": 5.0,
                    "options": {
                        "raise_warning": false,
                        "ignore_na": true
                    }
                },
                "less_than_or_equal_to": {
                    "value": 20.0,
                    "options": {
                        "raise_warning": false,
                        "ignore_na": true
                    }
                }
            },
            "unique": false,
            "coerce": false,
            "required": true,
            "regex": false
        },
        "column2": {
            "title": null,
            "description": null,
            "dtype": "object",
            "nullable": false,
            "checks": null,
            "unique": false,
            "coerce": false,
            "required": true,
            "regex": false
        },
        "column3": {
            "title": null,
            "description": null,
            "dtype": "datetime64[ns]",
            "nullable": false,
            "checks": {
                "greater_than_or_equal_to": {
                    "value": "2010-01-01 00:00:00",
                    "options": {
                        "raise_warning": false,
                        "ignore_na": true
                    }
                },
                "less_than_or_equal_to": {
                    "value": "2012-01-01 00:00:00",
                    "options": {
                        "raise_warning": false,
                        "ignore_na": true
                    }
                }
            },
            "unique": false,
            "coerce": false,
            "required": true,
            "regex": false
        }
    },
    "checks": null,
    "index": [
        {
            "title": null,
            "description": null,
            "dtype": "int64",
            "nullable": false,
            "checks": {
                "greater_than_or_equal_to": {
                    "value": 0.0,
                    "options": {
                        "raise_warning": false,
                        "ignore_na": true
                    }
                },
                "less_than_or_equal_to": {
                    "value": 2.0,
                    "options": {
                        "raise_warning": false,
                        "ignore_na": true
                    }
                }
            },
            "name": null,
            "unique": false,
            "coerce": false
        }
    ],
    "dtype": null,
    "coerce": true,
    "strict": false,
    "name": null,
    "ordered": false,
    "unique": null,
    "report_duplicates": "all",
    "unique_column_names": false,
    "add_missing_columns": false,
    "title": null,
    "description": null
}

您可以编辑此json文件以根据需要更新架构,然后使用 from_json()from_json() 将其加载回 pandera 架构对象。