randomSteph
randomSteph

Reputation: 43

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 ?

Upvotes: 4

Views: 2609

Answers (1)

ritchie46
ritchie46

Reputation: 14710

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)

Upvotes: 7

Related Questions