[Python] Can you create multiple columns based on the same set of conditions in Polars?

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

  1. Stack

    Stack Membro Participativo

    Is it possible to do something like this in Polars? Like do you need a separate when.then.otherwise for each of the 4 new varialbles, or can you use struct to create multiple new variables from one when.then.otherwise?

    Regular Python example:

    if x=1 and y=3 and w=300*z and z<100:
    tot = 300
    work = 400
    sie = 500
    walk = 'into'
    else:
    tot = 350
    work = 400*tot
    sie = tot/1000
    walk = 'outof'


    I tried to do a similar thing in Polars with struct (to create new variables a and b based on Movie variable:

    import polars as pl

    ratings = pl.DataFrame(
    {
    "Movie": ["Cars", "IT", "ET", "Cars", "Up", "IT", "Cars", "ET", "Up", "Cars"],
    "Theatre": ["NE", "ME", "IL", "ND", "NE", "SD", "NE", "IL", "IL", "NE"],
    "Avg_Rating": [4.5, 4.4, 4.6, 4.3, 4.8, 4.7, 4.5, 4.9, 4.7, 4.6],
    "Count": [30, 27, 26, 29, 31, 28, 28, 26, 33, 28],
    }
    )

    x = ratings.with_columns(
    pl.when(pl.col('Movie')=='Up').then(pl.struct(pl.lit(0),pl.lit(2))).otherwise(pl.struct(pl.lit(1),pl.lit(3))).struct.field(['a','b'])
    )
    print(x)


    Thanks!

    Continue reading...

Compartilhe esta Página