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

如何在Polars中筛选任意列包含特定值的所有行(附Pandas实现对比)

Polars中筛选至少含一个"Yes"的行

Hi there! Since you already know how to do this in Pandas, translating that logic to Polars is straightforward—here's how you can achieve the same result:

Step-by-Step Implementation

First, let's start with your existing Polars DataFrame, then apply the filter:

import polars as pl
df = pl.from_repr("""
┌─────┬─────┬─────┐
│ a   ┆ b   ┆ c   │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═════╪═════╪═════╡
│ Yes ┆ No  ┆ No  │
│ No  ┆ No  ┆ No  │
│ Yes ┆ No  ┆ Yes │
└─────┴─────┴─────┘
""")

# Filter rows where at least one column equals "Yes"
filtered_df = df.filter(pl.any_horizontal(pl.all().eq("Yes")))
print(filtered_df)

What This Code Does

Let's break it down to match your Pandas logic:

  • pl.all().eq("Yes"): Checks every column to see if each element is equal to "Yes", returning a boolean DataFrame (just like df_pd.eq('Yes') in Pandas).
  • pl.any_horizontal(): Runs a row-wise OR operation on those boolean values—this is the equivalent of any(axis=1) in Pandas, returning True for any row that has at least one "Yes".
  • .filter(): Uses those boolean results to keep only the rows that match the condition, just like df_pd.loc[...].

Output

Running the code will give you exactly the result you want:

┌─────┬─────┬─────┐
│ a   ┆ b   ┆ c   │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═════╪═════╪═════╡
│ Yes ┆ No  ┆ No  │
│ Yes ┆ No  ┆ Yes │
└─────┴─────┴─────┘

Optional: Explicit Column Selection

If you prefer to specify columns explicitly (instead of using pl.all()), you can write it like this too—great for clarity when working with larger datasets:

filtered_df = df.filter(pl.any_horizontal(pl.col("a", "b", "c").eq("Yes")))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 12:53:17