[Python] Declare intermediate variables in select statements in Polars

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    When writing select or with_columns statements in Polars I often wish to declare intermediate variables to make the code more readable. I'd also like to be able to query a column in a context and reuse it in another column's expression. I am currently forced to chain multiple select/with_columns calls which lacks elegance. Here is a fictive example of what I would like to do:

    df.with_columns(
    [
    <some expression>.alias('step_1'), # here I want step_1 to become a column in the output table
    temporary_variable = <some other expression>, # here I want this variable not to be present in the output table
    pl.col(['step_1']).some_function(temporary_variable).alias('step_2'), # this column's expression uses both the first column: 'step_1' and temporary_variable
    pl.col(...).some_other_function(temporary_variable).alias('another_column') # temporary_variable might need to be used in multiple column's expression, being able to declare the temporary variable and reuse it makes the code shorter, more modular and avoids copy pasts
    ]
    )


    My question is: is there any way to do this in Polars?

    Continue reading...

Compartilhe esta Página