Search code examples
pythonpython-polars

Replace nan values in a column with values from a different column from the same df in polars


I'm very new to polars and i'm trying to translate some pandas statements.

The pandas line is as follows:

df.loc[df['col_x'].isna(), 'col_y'] = df['col_z']

that is to say: replace the values of col_y corresponding to null values of col_x with values of col_z.

In polars i'm trying with select, but to no avail.


Solution

  • Here you have the solution for Polars and Pandas:
    Polars:

    df = (
        df
        .with_columns(pl.when(pl.col('col_x').is_nan()).then(pl.col('col_z'))
                  .otherwise(pl.col('col_y')).alias('col_y'))
    )
    

    Pandas:

    df["col_y"] = np.where(pd.isnull(df['col_x']), df['col_z'], df['col_y'])
    

    I hope this helps!