← 研究笔记
将数据假设写成代码:运行 Great Expectations

将数据假设写成代码:运行 Great Expectations

记录在屏蔽网络访问后运行 Great Expectations 的过程。它可以定义并验证数据要求,并检测出了我们引入的三类无效数据。

本文涉及的仓库

great-expectations/great_expectations

Always know what to expect from your data.

11.6k Python Apache License 2.0

你可以把“这一列不能包含空值”和“这个值应当处于 0 到 120 之间”这样的假设记在脑中。但流水线的一次改动,可能在不报错的情况下破坏这些假设。Great Expectations 允许你把数据必须满足的条件明确写成代码,再用真实数据对其进行验证。我安装了它,屏蔽了网络访问,并执行了验证。

Great Expectations 将每一项数据要求称为一个“Expectation”。你可以在代码中定义每项要求,针对一个数据框进行验证,并报告结果。该项目以 Apache 2.0 License(*1) 发布源代码。

1. 安装

FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'great_expectations==1.19.0' 'pandas==2.3.3'
WORKDIR /work
podman build -t great-expectations-sandbox .

2. 加入无效数据并进行验证

我准备了一个包含三类无效数据的数据框:为空的用户 ID、超出范围的年龄,以及格式错误的电子邮箱地址。接着,我定义了对应的 Expectations,屏蔽网络访问,并运行了验证。

import pandas as pd
import great_expectations as gx

df = pd.DataFrame({
    "user_id": [1, 2, 3, 4, 5, None],
    "age": [25, 34, -3, 41, 150, 29],
    "email": ["a@example.com", "b@example.com", "not-an-email", "d@example.com", "e@example.com", "f@example.com"],
})

context = gx.get_context(mode="ephemeral")
data_source = context.data_sources.add_pandas("demo_source")
data_asset = data_source.add_dataframe_asset(name="demo_asset")
batch_definition = data_asset.add_batch_definition_whole_dataframe("demo_batch")
batch = batch_definition.get_batch(batch_parameters={"dataframe": df})

suite = gx.ExpectationSuite(name="demo_suite")
suite.add_expectation(gx.expectations.ExpectColumnValuesToNotBeNull(column="user_id"))
suite.add_expectation(gx.expectations.ExpectColumnValuesToBeBetween(column="age", min_value=0, max_value=120))
suite.add_expectation(
    gx.expectations.ExpectColumnValuesToMatchRegex(column="email", regex=r"^[^@]+@[^@]+\.[^@]+$")
)

results = batch.validate(suite)
for result in results.results:
    print(result.expectation_config.type, "success:", result.success, "unexpected:", result.result.get("unexpected_count"))
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
  -v "$(pwd)":/work -w /work great-expectations-sandbox \
  python validate_demo.py

-v 选项允许容器从指定目录读取和写入文件。本次实验请使用一个空目录。

该命令生成了以下输出。

expect_column_values_to_not_be_null: success=False unexpected_count=1
expect_column_values_to_be_between: success=False unexpected_count=2
expect_column_values_to_match_regex: success=False unexpected_count=1

overall success: False

这次运行检测出了三类无效数据。它找到了一个为空的用户 ID、两个超出范围的年龄(-3 和 150),以及一个格式错误的电子邮箱地址。数量与预期一致。验证的总体结果也如预期为 False。

明确写出数据假设

如果你不把“这一列应当包含某种类型的值”这样的假设写下来,下一位接手流水线的人就不会知道它。使用 Great Expectations 将这个假设写成代码后,数据违反它时,验证失败就会显现出来。这样,你可以把数据质量检查与依赖某一个人的手动检查分开。

来源

*1 Great Expectations (GitHub), https://github.com/great_expectations/great_expectations, Apache 2.0 License