Filter rows in Polars Dataframe if a list column contains a specific value
19:31 11 Apr 2023

I want to filter a polars dataframe based in a column where the values are a list.

import polars as pl

df = pl.DataFrame(
{
    "foo": [[1, 3, 5], [2, 6, 7], [3, 8, 10]],
    "bar": [6, 7, 8],
    "ham": ["a", "b", "c"],
})

I want a filter that returns every row that column "foo" has the value 3.

shape: (2, 3)
┌────────────┬─────┬─────┐
│ foo        ┆ bar ┆ ham │
│ ---        ┆ --- ┆ --- │
│ list[i64]  ┆ i64 ┆ str │
╞════════════╪═════╪═════╡
│ [1, 3, 5]  ┆ 6   ┆ a   │
│ [3, 8, 10] ┆ 8   ┆ c   │
└────────────┴─────┴─────┘
python dataframe python-polars