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

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

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

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] │
└───────────────────┘
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