[Python] How to add numeric value from one column to other List column elements in Polars?

Discussão em 'Python' iniciado por Stack, Agosto 30, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I have the following Polars DataFame:

    import polars as pl

    df = pl.DataFrame({
    'lst': [[0, 1], [9, 8]],
    'val': [3, 4]
    })


    And I want to add the number in the val column, to every element in the corresponding list in the lst column, to get the following result:

    ┌───────────┬─────┐
    │ lst ┆ val │
    │ --- ┆ --- │
    │ list[i64] ┆ i64 │
    ╞═══════════╪═════╡
    │ [3, 4] ┆ 3 │
    │ [13, 12] ┆ 4 │
    └───────────┴─────┘


    I know how to add a constant value, e.g.:

    new_df = df.with_columns(
    pl.col('lst').list.eval(pl.element() + 2)
    )


    But when I try:

    new_df = df.with_columns(
    pl.col('lst').list.eval(pl.element() + pl.col('val'))
    )


    I get the following error:

    polars.exceptions.ComputeError: named columns are not allowed in `list.eval`; consider using `element` or `col("")`


    Is there any elegant way to achieve my goal (without map_elements)?

    Thanks in advance.

    Continue reading...

Compartilhe esta Página