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

如何在Polars中按行计算True值的数量?

在Polars中按行统计布尔值True的数量

在Polars 0.16.18版本中,直接使用sum(axis=1)统计每行的True数量会触发PanicException,因为布尔类型不支持行方向的加法操作,但列方向的统计可以正常工作。以下是几种可行的解决方法:

方法1:将布尔列转换为数值类型后按行求和

先把布尔列转为整数类型(True对应1,False对应0),再执行行方向的求和:

import polars as pl

s = pl.DataFrame({"a": [True, False, True], "b":[True, True, False]})
# 添加行统计列
result = s.with_columns(
    row_true_count=pl.col(pl.Boolean).cast(pl.UInt32).sum(axis=1)
)
print(result)

输出结果:

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

方法2:使用sum_horizontal函数

sum_horizontal是Polars专门用于行方向求和的函数,配合类型转换可以直接实现需求:

result = s.with_columns(
    row_true_count=pl.sum_horizontal(pl.col(pl.Boolean).cast(pl.UInt32))
)
print(result)

方法3:使用fold函数累加

通过fold函数逐列累加转换后的布尔值,适合需要自定义累加逻辑的场景:

result = s.with_columns(
    row_true_count=pl.fold(
        acc=pl.lit(0, dtype=pl.UInt32),
        f=lambda acc, col: acc + col.cast(pl.UInt32),
        exprs=pl.col(pl.Boolean)
    )
)
print(result)

原因说明

Polars在旧版本中,列方向的sum会隐式将布尔值视为1/0进行统计,但行方向的sum(底层调用hsum)没有做这个隐式转换,因为布尔类型的加法操作在语义上不被支持,所以需要手动转换为数值类型后再执行行求和。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:14:53