[Python] How can I optionally apply filtering to a Polars dataframe

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    I want to apply filtering to Polars Dataframe, but each element of the filter is optional, dependent on the availablity of a function parameter.

    I have a function that takes the following 3 paramters: ticker: str = '', strategy: str = '', iteration: int = -1

    If these parameters are not the default value then I want to apply that filter to the dataframe. My logic is as follows:

    self.configs_df = self.configs_df.filter(
    (ticker != '' & pl.col('Ticker') == ticker) &
    (strategy != '' & pl.col('Strategy') == strategy) &
    (iteration >= 0 & pl.col('Iteration') == iteration)
    )


    but I get an error: TypeError: the truth value of an Expr is ambiguous which I understand, but I don't know how to build the expression up in its logical parts. Any help or guidance would be much appreciated as I am an absolute beginner with Polars, having come from Pandas, where I have this (similar) logic working.

    Regards, Stuart

    Continue reading...

Compartilhe esta Página