[Python] filter polars dataframe using a variable

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

  1. Stack

    Stack Membro Participativo

    I have a polars datraframe

    I have a complex filter created, and put into a variable

    I want to use the variable to filter the polars dataframe, but receive the error: TypeError: invalid predicate for filter. Is there a way around this?

    MRE:

    df=pd.DataFrame({'col1':[1,2,3,4,5], 'col2':[6,7,8,9,9], 'col3':[11,12,13,14,15]})
    str_filter = 'col1 > 3'
    df.query(str_filter) ### WORKS
    dp = pl.from_pandas(df)
    dp.filter(pl.col('col1')>3) ### WORKS
    str_filter = "pl.col('col1')>3"
    dp.filter(str_filter) ### ERROR

    TypeError: invalid predicate for `filter`: "pl.col('col1')>3"

    Continue reading...

Compartilhe esta Página