Given a sample DataFrame df
>>> df = pl.DataFrame({'l': [3,5,8]})
>>> df
shape: (3, 1)
┌─────┐
│ l │
│ --- │
│ i64 │
╞═════╡
│ 3 │
│ 5 │
│ 8 │
└─────┘
How do I make a new column that looks like this?
>>> df
shape: (3, 2)
┌─────┬─────────────┐
│ l ┆ column_0 │
│ --- ┆ --- │
│ i64 ┆ list[i64] │
╞═════╪═════════════╡
│ 3 ┆ [0, 1, 2] │
│ 5 ┆ [0, 1, … 4] │
│ 8 ┆ [0, 1, … 7] │
└─────┴─────────────┘
This is my best way of doing it but it is using map_rows, not so efficient when things scale up
>>> temp = df.map_rows(lambda x: (list(range(x[0])),))
>>> df = df.hstack(temp)
For this, pl.int_ranges can be used.
import polars as pl
df = pl.DataFrame({
"length": [3,5,8]
})
df.with_columns(
pl.int_ranges("length").alias("list")
)
shape: (3, 2)
┌────────┬─────────────┐
│ length ┆ list │
│ --- ┆ --- │
│ i64 ┆ list[i64] │
╞════════╪═════════════╡
│ 3 ┆ [0, 1, 2] │
│ 5 ┆ [0, 1, … 4] │
│ 8 ┆ [0, 1, … 7] │
└────────┴─────────────┘
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With