如何在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 likedf_pd.eq('Yes')in Pandas).pl.any_horizontal(): Runs a row-wise OR operation on those boolean values—this is the equivalent ofany(axis=1)in Pandas, returningTruefor any row that has at least one "Yes"..filter(): Uses those boolean results to keep only the rows that match the condition, just likedf_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
相关产品推荐
相关产品推荐

