英文:
Python Polars - Create sequence in list from integer
问题
考虑到:
强烈不建议使用apply,因为这实际上相当于运行Python的“for”循环。这样会非常慢。在可能的情况下,您应该尽量使用原生表达式API以获得最佳性能。
我该如何使用Polars的原生表达式API来生成一个新列,其中包含从1到另一列中的数字的列表?
也就是说,从这个:
变成这个:
使用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:
To this:
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
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] │
└─────┴───────────┘
英文:
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] │
└─────┴───────────┘
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论