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

如何在Polars中按条件检测缺失值并实现例外规则?

问题描述

现有一段Polars代码用于生成缺失值报告,逻辑是识别**含缺失值且mandatory列为"M"**的行,同时添加index行号列和warning提示列:

report = (df.with_row_count("index")
                .filter(pl.any(pl.col("*").is_null()) & pl.col("mandatory").eq("M"))
                .with_columns(pl.lit("Missing value detected").alias("warning"))
         )

需新增规则:若column列值相同的组内存在**无缺失值且mandatory为"M"**的行,则该组内其他符合原规则的行不纳入报告。

示例数据集:

df = pl.DataFrame(
    {
        "ID": ["1", "1", "1", "1", "1"],
        "column": ["foo", "foo", "bar", "ham", "egg"],
        "table": ["A", "B", "C", "D", "E"],
        "value_a": ["tree", None, None, "bean", None,],
        "value_b": ["Lorem", "Ipsum", "Dal", "Curry", "Dish",],
        "mandatory": ["M", "M", "M", "CM", "M"],
    }
)

示例中foo组存在无缺失值的M行,因此该组内有缺失值的M行需排除,最终报告应仅包含bar和egg对应的行。

解决方案

可以通过分组标记组内是否存在有效行,再结合原规则过滤,代码如下:

report = (
    df.with_row_count("index")
    # 标记每行是否符合原规则(含缺失值且mandatory为"M")
    .with_columns(
        is_target = pl.any(pl.col("*").is_null()) & pl.col("mandatory").eq("M"),
        # 标记该行是否为组内的有效行(无缺失值且mandatory为"M")
        is_valid = pl.all(pl.col("*").is_not_null()) & pl.col("mandatory").eq("M")
    )
    # 按column分组,判断组内是否存在有效行
    .with_columns(
        has_valid_in_group = pl.col("is_valid").any().over("column")
    )
    # 过滤:符合原规则,且组内无有效行
    .filter(pl.col("is_target") & ~pl.col("has_valid_in_group"))
    # 添加警告列
    .with_columns(pl.lit("Missing value detected").alias("warning"))
    # 移除辅助计算列(可选)
    .drop("is_target", "is_valid", "has_valid_in_group")
)

逻辑说明:

  • is_target:标记出原本符合条件的行(含缺失值+mandatory为"M");
  • is_valid:标记组内的“有效行”——无缺失值且mandatory为"M"的行;
  • has_valid_in_group:通过over("column")分组聚合,判断每个column组是否存在至少一个有效行;
  • 最终过滤时,仅保留符合原规则且所在组无有效行的行,满足新增规则要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:08:11