[Python] Setting slice of column to list of values on polars dataframe

Discussão em 'Python' iniciado por Stack, Dezembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    In the code below I'm creating a polars- and a pandas dataframe with identical data. I want to select a set of rows based on a condition on column A, then update the corresponding rows for column C. I've included how I would do this with the pandas dataframe, but I'm coming up short on how to get this working with polars. The closest I've gotten is by using when-then-otherwise, but I'm unable to use anything other than a single value in then.

    import pandas as pd
    import polars as pl

    df_pd = pd.DataFrame({'A': ['x', 'x', 'x', 'x', 'y', 'y', 'y', 'y'],
    'B': [1, 1, 2, 2, 1, 1, 2, 2],
    'C': [1, 2, 3, 4, 5, 6, 7, 8]})

    df_pl = pl.DataFrame({'A': ['x', 'x', 'x', 'x', 'y', 'y', 'y', 'y'],
    'B': [1, 1, 2, 2, 1, 1, 2, 2],
    'C': [1, 2, 3, 4, 5, 6, 7, 8]})

    df_pd.loc[df_pd['A'] == 'x', 'C'] = [-1, -2, -3, -4]

    df_pl ???

    Continue reading...

Compartilhe esta Página