Search code examples
pythonlistpython-polars

How to change a list element by index in a list column


I have a column of lists in my polars dataframe. I would like to access and change a value by list index.

Example input

df = pl.DataFrame({
    "values": [
        [10, 20, 30, 40], 
        [50, 60, 70, 80], 
        [90, 100, 110, 120],
    ],
})

Pseudocode

df = df.with_columns(
    pl.col("values").list.eval(pl.element(3) = 1).alias("values2")
)

Expected outcome

df = pl.DataFrame({
    "values": [
        [10, 20, 30, 1], 
        [50, 60, 70, 1], 
        [90, 100, 110, 1],
    ],
})

Solution

    • take first 3 elements with list.head().
    • add 1
    • add remaining elements of list with list.tail() using -4 to get all elements except first 4.
    • concat_list() to concat elements together.
    df.with_columns(
        pl.concat_list(
            pl.col.values.list.head(3), 1,
            pl.col.values.list.tail(-4)
        )
    )
    
    shape: (3, 1)
    ┌───────────────────┐
    │ values            │
    │ ---               │
    │ list[i64]         │
    ╞═══════════════════╡
    │ [10, 20, 30, 1]   │
    │ [50, 60, 70, 1]   │
    │ [90, 100, 110, 1] │
    └───────────────────┘