Python Polars – Create sequence in list from integer

huangapple go评论75阅读模式
英文:

Python Polars - Create sequence in list from integer

问题

考虑到:

强烈不建议使用apply,因为这实际上相当于运行Python的“for”循环。这样会非常慢。在可能的情况下,您应该尽量使用原生表达式API以获得最佳性能。

我该如何使用Polars的原生表达式API来生成一个新列,其中包含从1到另一列中的数字的列表?

也就是说,从这个:

Python Polars – Create sequence in list from integer

变成这个:

Python Polars – Create sequence in list from integer

使用apply:

# 导入包
import polars as pl

# 创建DataFrame
df = pl.DataFrame({'Qty': [1, 2, 3]})

# 添加'List'列
df = df.with_columns(
    pl.col('Qty').apply(lambda x: [i+1 for i in range(x)]).alias('List')
)
英文:

Considering that:

> Using apply is strongly discouraged as you will be effectively running python “for” loops. This will be very slow. Wherever possible you should strongly prefer the native expression API to achieve the best performance.

How can I use Polars native expression API to generate a new column with a list containing all the integers from 1 to the number of another column?

This means, going from this:

Python Polars – Create sequence in list from integer

To this:

Python Polars – Create sequence in list from integer

Using apply:

# Import package.
import polars as pl

# Create the DataFrame.
df = pl.DataFrame({'Qty': [1, 2, 3]})

# Add the 'List' column.
df = df.with_columns(
    pl.col('Qty').apply(lambda x: [i+1 for i in range(x)]).alias('List')
)

答案1

得分: 2

pl.int_ranges()

df.with_columns(list = pl.int_ranges(1, pl.col("Qty") + 1))
形状: (3, 2)
┌─────┬───────────┐
│ Qty ┆ list      │
│ --- ┆ ---       │
│ i64 ┆ list[i64] │
╞═════╪═══════════╡
│ 1   ┆ [1]       │
│ 2   ┆ [1, 2]    │
│ 3   ┆ [1, 2, 3] │
└─────┴───────────┘
英文:

pl.int_ranges()

df.with_columns(list = pl.int_ranges(1, pl.col("Qty") + 1))
shape: (3, 2)
┌─────┬───────────┐
│ Qty ┆ list      │
│ --- ┆ ---       │
│ i64 ┆ list[i64] │
╞═════╪═══════════╡
│ 1   ┆ [1]       │
│ 2   ┆ [1, 2]    │
│ 3   ┆ [1, 2, 3] │
└─────┴───────────┘

huangapple
  • 本文由 发表于 2023年8月9日 01:47:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定