Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a python list to another list (Series) of a polars-dataframe?

I have a polars dataframe like this:

test=pl.DataFrame({"myColumn": [[1,2,3],[1,2,3],[1,2,3]]})

Now i would like to append list elements from another list, lets say [4,5] to each of the entries, so to get [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

Q1: How would that be done ? Q2: What would be an approach to make it fast ?

like image 864
randomSteph Avatar asked Sep 15 '25 19:09

randomSteph


1 Answers

Polars Series/columns of dtype List have a .list namespace. You can use the list.concat method to append a list.

df = pl.DataFrame({"my_column": [[1,2,3],[1,2,3],[1,2,3]]})
df.with_columns(pl.col("my_column").list.concat([4, 5]))

The output is:

shape: (3, 1)
┌─────────────────┐
│ my_column       │
│ ---             │
│ list[i64]       │
╞═════════════════╡
│ [1, 2, 3, 4, 5] │
│ [1, 2, 3, 4, 5] │
│ [1, 2, 3, 4, 5] │
└─────────────────┘

(note: we used pl.Config(fmt_table_cell_list_len=-1) to change the default repr)

like image 155
ritchie46 Avatar answered Sep 17 '25 10:09

ritchie46