Polars 的核心思想一句话就能说完:你不用告诉它怎么算一列,只需描述这一列,由它决定怎么算。pl.col("close") / pl.col("open") - 1 是一个对象,即一个表达式。把它放进 select 或 filter 之类的上下文之前,什么都不会被计算;放进去之后,Polars 会在所有核心上并行地对整列执行它。
用通俗的话说这个想法
我们在哪里。 主题 1 读取并检查了一个数据框。这个主题是后面所有内容的词汇:分组、窗口、连接和时间,都是处在不同上下文中的表达式。这也是 Polars 与 pandas 差别最大的地方:pandas 会写逐单元格的循环或 apply,而 Polars 只写一个表达式。
对列计算的一种描述,Polars 可以稍后并行地对整列执行它。它由 pl.col、pl.lit、算术运算和方法构成,只有放进 select、with_columns 或 filter 等上下文中才会产生值。
添加列并保留行
with_columns 接受任意多个表达式,并把每个表达式添加为一列;alias 给结果命名。同一次调用里的表达式相互独立,所以 Polars 会让它们并排执行。filter 接受一个布尔表达式,保留其为真的行。这里 .abs() 是表达式上的方法,因此大跌和大涨都算作大幅波动。
# Two new columns in one call: the day's range and its returnwide = with_range(df)print(wide.columns[-2:])print(wide.select(pl.col("range_pct").max().alias("widest range"), pl.col("return_pct").min().alias("worst day")).row(0))
['range_pct', 'return_pct'] (0.2732250486450573, -0.15722320825938052)
# Days when the stock moved more than 10% from open to close, either waybig = big_moves(df, 0.10)print(big.height, "of", df.height, "days")print(big.select("symbol").to_series().value_counts().sort("symbol").rows())
50 of 33493 days
[('AAPL', 14), ('JPM', 31), ('XOM', 5)]用 when/then 按行选择
pl.when(condition).then(value).otherwise(other) 是 if/else 的表达式形式。它对每一行同时计算条件并按行选取值,追加 .when(...).then(...) 分支可处理更多情形。direction_label 用它给上涨、下跌和持平的日子贴标签,无需 Python 的 if。price_view 展示了 select,它只返回你构造的列,并按你列出的顺序排列。
# up / down / flat labels, counted by labellabelled = direction_label(df)print(labelled["direction"].value_counts().sort("direction").rows())
[('down', 16112), ('flat', 193), ('up', 17188)]# A trimmed view: symbol, date, px and the typical priceview = price_view(df)print(view.columns)print(view.head(3))
['symbol', 'date', 'px', 'typical'] shape: (3, 4) ┌────────┬────────────┬──────────┬──────────┐ │ symbol ┆ date ┆ px ┆ typical │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ date ┆ f64 ┆ f64 │ ╞════════╪════════════╪══════════╪══════════╡ │ AAPL ┆ 2000-01-03 ┆ 0.83826 ┆ 0.814089 │ │ AAPL ┆ 2000-01-04 ┆ 0.76771 ┆ 0.784849 │ │ AAPL ┆ 2000-01-05 ┆ 0.778895 ┆ 0.792829 │ └────────┴────────────┴──────────┴──────────┘
map_elements 和 iter_rows 每行运行一次 Python,放弃了并行的编译路径,常常慢上百倍。几乎所有的列计算都有表达式形式:算术、比较、when/then、字符串和日期方法。主题 10 会讲少数没有表达式形式的情况,但请先假设总有一种存在。
任务要求
- 1`with_range` 与 `price_view`
df.with_columns(expr.alias(...), ...)用于添加;df.select(expr, ...)构建新数据框。 - 2`big_moves`
df.filter((pl.col("close") / pl.col("open") - 1).abs() > threshold)。 - 3`direction_label`
pl.when(cond).then(pl.lit("up")).when(cond2).then(pl.lit("down")).otherwise(pl.lit("flat")),别名direction。
df.with_columns(pl.col("close") / pl.col("open") - 1) 比用 Python 遍历行更好?实验:评分内容
4 个任务 · 100 分- 添加列:
with_range25 分 - 保留大波动日:
big_moves25 分 - 按行选择:
direction_label25 分 - 选取并重命名:
price_view25 分