← 研究筆記
將資料假設寫成程式碼:執行 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