You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Great Expectations验证数组列中的元素是否属于指定集合?

解决Great Expectations检查数组列元素归属的问题

问题背景

有一个包含数组列的pandas DataFrame:

import pandas as pd

df = pd.DataFrame(
    data={
        "request_id": [1, 2, 3, 4, 5],
        "failure_reasons": [
            [],
            ["reason_5"],
            ["reason_2", "reason_3"],
            ["reason_1", "reason_2", "reason_3", "reason_4", "reason_5"],
            [],
        ]
    }
)

需要验证failure_reasons列中所有数组内的元素都属于{"reason_1", "reason_2", "reason_3", "reason_4", "reason_5"}集合,但使用expect_column_distinct_values_to_be_in_set时出现错误:

MetricResolutionError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

错误原因是该期望会把列中的每个数组当作整体去和value_set中的单个字符串比较,导致逻辑歧义。

解决方案

方案1:预处理DataFrame,展开数组列

先将数组列展开为多行,再对展开后的列进行验证:

import great_expectations as gx

# 预处理:展开数组列
exploded_df = df.explode("failure_reasons", ignore_index=True)
exploded_df.to_parquet("../gx_datasets/data_exploded.parquet")

# 初始化GX上下文并读取处理后的数据
context = gx.get_context()
validator = context.sources.pandas_default.read_parquet("../gx_datasets/data_exploded.parquet")

# 验证展开后的列
validator.expect_column_distinct_values_to_be_in_set(
    column="failure_reasons",
    value_set=["reason_1", "reason_2", "reason_3", "reason_4", "reason_5"],
    # 排除空值(原数组为空时展开后会生成NaN)
    mostly=1.0,
    condition="failure_reasons IS NOT NULL"
)

方案2:使用自定义条件验证(无需修改原始数据)

利用expect_column_values_to_satisfy_condition,传入自定义函数检查每个数组内的所有元素都在预期集合中:

import great_expectations as gx

# 读取原始数据
context = gx.get_context()
validator = context.sources.pandas_default.read_parquet("../gx_datasets/data.parquet")

# 定义预期集合
allowed_reasons = {"reason_1", "reason_2", "reason_3", "reason_4", "reason_5"}

# 使用自定义条件验证
validator.expect_column_values_to_satisfy_condition(
    column="failure_reasons",
    condition=lambda x: all(reason in allowed_reasons for reason in x)
)

这个方法直接对每行的数组进行检查,确保数组内所有元素都属于允许集合,空数组会自动通过验证(all()对空迭代器返回True)。


内容的提问来源于stack exchange,提问作者anajbellini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 10:22:41