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

如何检测Polars DataFrame中是否存在True值?

如何简洁检测Polars DataFrame中是否存在任意True值?

假设你有这样一个全布尔类型的Polars DataFrame:

import polars as pl

df = pl.from_repr("""
┌───────┬───────┬───────┐
│ a     ┆ b     ┆ c     │
│ ---   ┆ ---   ┆ ---   │
│ bool  ┆ bool  ┆ bool  │
╞═══════╪═══════╪═══════╡
│ false ┆ true  ┆ false │
│ false ┆ false ┆ false │
│ false ┆ false ┆ false │
└───────┴───────┴───────┘
""")

你之前的方案需要多步操作才能得到最终结果,其实有几种更简洁的写法可以直接返回布尔值:

  • 方法一:链式聚合判断
    先计算每一列是否存在True,再对这些结果做一次聚合判断:

    df.select(pl.all().any().any()).item()
    
  • 方法二:用any_vertical直接跨行跨列判断
    any_vertical可以对所有列的元素进行纵向判断,直接得到整个DataFrame是否有True:

    df.select(pl.any_vertical(pl.all())).item()
    
  • 方法三:扁平化后直接判断
    把整个DataFrame转换成单个Series,再调用any()方法:

    df.to_series().any()
    

以上三种方法都能一步得到结果,不需要额外的行检查步骤。针对示例中的DataFrame,三种方法都会返回True,因为其中存在True值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:19:58