如何使用Polars表达式实现与Pandas等效的按列条件求和?
Polars实现指定条件的rebounds列求和
需求:筛选出points≥8且team≠'B'的行,对rebounds列求和,最终结果为20。以下是对应Polars的几种实现方式:
示例数据
import polars as pl df = pl.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'C'], 'conference': ['East', 'East', 'East', 'West', 'West', 'East'], 'points': [11, 8, 10, 6, 6, 5], 'rebounds': [7, 7, 6, 9, 12, 8]})
Polars实现代码
方式1:先筛选行再求和
和Pandas的loc写法逻辑匹配,先过滤符合条件的行,再提取rebounds列求和:
df.filter((pl.col("points") >= 8) & (pl.col("team") != "B"))["rebounds"].sum() # 输出:20
方式2:用列表达式直接计算(推荐的Polars风格)
在select中通过表达式直接对满足条件的rebounds值求和,最后用item()提取标量结果:
df.select( pl.col("rebounds").filter((pl.col("points") >= 8) & (pl.col("team") != "B")).sum() ).item() # 输出:20
方式3:使用query方法(类似Pandas的query)
Polars支持类SQL的查询语法,写法和Pandas的query几乎一致:
df.query("points >= 8 and team != 'B'")["rebounds"].sum() # 输出:20
内容的提问来源于stack exchange,提问作者codedancer
相关产品推荐
相关产品推荐

