Polars如何检查DataFrame中是否存在任何空值?
判断Polars DataFrame中是否存在空值
已知使用df.null_count()可以获取DataFrame各列的空值数量,但直接用if any(df.null_count()):无法生效——因为null_count()返回的是单行DataFrame对象,而非可直接迭代的序列,any()无法正确解析该结构。
以下是几种正确的实现方式:
方法1:转换null_count结果为可迭代结构
将null_count()返回的DataFrame转为numpy数组后,再用any()判断:
import polars as pl data = {"foo": [1, 2, 3, None], "bar": [4, None, None, 6]} df = pl.DataFrame(data) has_nulls = df.null_count().to_numpy().any() print(has_nulls) # 输出: True
方法2:使用Polars表达式高效判断
通过any_horizontal直接检查所有列是否存在空值,无需生成完整的空值计数,性能更优:
has_nulls = df.select(pl.any_horizontal(pl.all().is_null())).item() print(has_nulls) # 输出: True
方法3:链式调用is_null与any
先对整个DataFrame标记空值,再通过两次any()判断(第一次判断每列是否有至少一个空值,第二次判断所有列的结果):
has_nulls = df.is_null().any().any() print(has_nulls) # 输出: True
内容的提问来源于stack exchange,提问作者user3240688
相关产品推荐
相关产品推荐

