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

Viewed 361

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 ?

1 Answers

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

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

The output is:

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

Related