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

如何在Python Polars中实现含Null的DataFrame逐单元格比较

在Polars中处理含Null值的DataFrame逐单元格比较

要实现两边均为Null时返回True,仅一边为Null时返回False的全布尔比较结果,有两种实用方法:

方法1:使用内置的eq_missing方法(优先推荐)

Polars内置的eq_missing方法专门针对含缺失值的相等性比较设计,完全匹配你的需求:

  • 两个单元格均为Null时,返回True
  • 仅一边为Null时,返回False
  • 非Null值时,按常规==逻辑做比较

示例代码

import polars as pl

# 创建示例DataFrame
df1 = pl.DataFrame({
    "a": [1, None, 3, None],
    "b": ["x", "y", None, None]
})

df2 = pl.DataFrame({
    "a": [1, 2, None, None],
    "b": ["x", None, None, "z"]
})

# 执行带Null处理的比较
result = df1.eq_missing(df2)
print(result)

输出结果

shape: (4, 2)
┌───────┬───────┐
│ a     ┆ b     │
│ ---   ┆ ---   │
│ bool  ┆ bool  │
╞═══════╪═══════╡
│ true  ┆ true  │
│ false ┆ false │
│ false ┆ true  │
│ true  ┆ false │
└───────┴───────┘

方法2:手动构造比较逻辑(自定义场景适用)

如果需要更灵活的自定义判断逻辑,可以用pl.when分支语句实现:

示例代码

def compare_df_with_null(df1, df2):
    # 确保两个DataFrame列名一致
    assert df1.columns == df2.columns, "DataFrames必须拥有相同列名"
    
    return df1.select([
        pl.when((pl.col(c).is_null()) & (df2[c].is_null()))
        .then(True)
        .when((pl.col(c).is_null()) ^ (df2[c].is_null()))  # 异或判断仅一边为Null
        .then(False)
        .otherwise(pl.col(c) == df2[c])
        .alias(c)
        for c in df1.columns
    ])

# 调用函数
result = compare_df_with_null(df1, df2)
print(result)

这个方法逻辑清晰:先处理两边均为Null的情况,再处理仅一边为Null的情况,最后用常规相等比较处理非Null值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:52:07