pythondataframelistpython-polarspolars

Using a list of values to select rows from Polars DataFrame


I have a Polars DataFrame below:

import polars as pl
df = pl.DataFrame({"a":[1, 2, 3], "b":[4, 3, 2]})

>>> df
  a    b
i64  i64
  1    4
  2    3
  3    2

I can subset based on a specific value:

x = df[df["a"] == 3]

>>> x
  a    b
i64  i64
  3    2

But how can I subset based on a list of values? - something like this:

list_of_values = [1, 3]
y = df[df["a"] in list_of_values]

To get:

  a    b
i64  i64
  1    4
  3    2

Solution

  • y = df.filter(pl.col("a").is_in(list_of_values))
    

    Output:

    ┌─────┬─────┐
    │ a   ┆ b   │
    │ --- ┆ --- │
    │ i64 ┆ i64 │
    ╞═════╪═════╡
    │ 1   ┆ 4   │
    │ 3   ┆ 2   │
    └─────┴─────┘