Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Polars: use value from column as column name in when then expression

In a polars dataframe I have a column that contains the names of other columns (column "id_column_name"). I want to use those names in a when-then expression with pl.col() to create a new column ("id") which gets its values out of these other columns ("id_column1", "id_column2"). Every row can gets its value from another column in the df.

# initial df
df = pl.DataFrame({
        'id_column1': [123, 456],
        'id_column2': ['abc', 'def'],
        'id_column_name': ['id_column1', 'id_column2']
})

# required output df
df = pl.DataFrame({
    'id_column1': [123, 456],
    'id_column2': ['abc', 'def'],
    'id_column_name': ['id_column1', 'id_column2'],
    'id': ['123', 'def'] 
})

# one of the trings I tried
df = df.with_columns([
    pl.when(pl.col('id_column_name').is_not_null())
    .then(pl.col(pl.col('id_column_name')))
    .otherwise(None)
    .cast(pl.Utf8)
    .alias('id')
])

This leads to the error: Expected str or DataType, got ‘Expr’.

Using str() or .str to create the expression into a regular string lead to other errors:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected str or DataType, got ‘ExprStringNameSpace’.

This cant be that hard, can it?

>Solution :

df.with_columns(
    id = pl.coalesce(
        pl.when(pl.col.id_column_name == col).then(pl.col(col))
        for col in df["id_column_name"].unique()
    )
)
shape: (2, 4)
┌────────────┬────────────┬────────────────┬─────┐
│ id_column1 ┆ id_column2 ┆ id_column_name ┆ id  │
│ ---        ┆ ---        ┆ ---            ┆ --- │
│ i64        ┆ str        ┆ str            ┆ str │
╞════════════╪════════════╪════════════════╪═════╡
│ 123        ┆ abc        ┆ id_column1     ┆ 123 │
│ 456        ┆ def        ┆ id_column2     ┆ def │
└────────────┴────────────┴────────────────┴─────┘
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading