Polars 是一个用 Rust 编写的高性能 DataFrame 库,面向速度与内存效率设计。与 pandas 在单核上顺序处理数据不同,Polars 会把操作并行化到所有可用 CPU 核心;其惰性 API 允许在真正执行前先优化查询,从而显著降低内存开销和处理时间。
用途与适用场景
根据资料,Polars 适合以下情况:
- 处理在 pandas 中难以应付的大数据集(1GB - 100GB+)。
- 对执行速度有较高要求(资料称 Polars 通常比 pandas 快 10-100 倍)。
- 构建复杂的数据转换管道(利用惰性求值)。
- 内存有限的系统(比 pandas 更节省内存)。
- 需要严格类型安全和一致空值处理的场景。
- 读写大型 Parquet、CSV 或 Avro 文件。
核心概念
即时 API 与惰性 API
- 即时(Eager):操作立即执行,类似 pandas。
- 惰性(Lazy):操作先排入查询计划,Polars 会优化该计划(如谓词下推、投影下推),只在调用收集时执行。
表达式 API
- Polars 使用声明式语法,用 pl.col() 编写表达式,而不是写循环或复杂 lambda。这些表达式经过高度优化并并行运行。
Apache Arrow
- Polars 以 Apache Arrow 格式存储数据,可与 PyArrow、DuckDB 等工具零拷贝交换数据。
安装与导入
pip install polars
# 需要 Excel/云端支持时
pip install 'polars[all]'
import polars as pl
import numpy as np
基本用法:惰性工作流
资料给出的“Polars 方式”示例:
import polars as pl
# 1. 扫描(惰性)——此时不加载数据
lf = pl.scan_csv("massive_data.csv")
# 2. 构建查询计划
query = (
lf.filter(pl.col("age") > 25)
.group_by("city")
.agg([
pl.col("salary").mean().alias("avg_salary"),
pl.col("name").count().alias("count")
])
.sort("avg_salary", descending=True)
)
# 3. 收集(执行)
df = query.collect()
官方参考
- 官方文档:https://docs.pola.rs/
- 用户指南:https://docs.pola.rs/user-guide/
- 常用搜索模式:pl.DataFrame、pl.LazyFrame、pl.col、df.select、df.filter、df.group_by
使用建议(资料原文整理的 DO / DON'T)
推荐做法:
- 优先使用惰性 API(scan_*),让 Polars 优化内存并跳过不必要的数据。
- 使用表达式,始终用 pl.col("name") 而非字符串或索引选列。
- 使用方法链,Polars 为清晰可读的管道而构建。
- 读取 CSV 时指定 schema,避免类型推断错误并加快加载。
- 数据大于内存时使用 collect(streaming=True),分块处理。
- 永久存储优先用 Parquet,比 CSV 快得多且保留类型信息。
应避免:
- 避免 .apply():自定义 Python 函数会破坏 Rust/并行优化。
- 不要用 inplace=True:Polars 倾向不可变性,转换返回新 DataFrame。
- 不要过早转换为 pandas:尽量保持在 Polars 中以维持速度。
- 避免逐行迭代:for row in df 是反模式,应使用向量化表达式。
表达式 API 速览
选择与转换:
df.select([
pl.col("name"),
pl.col("price") * 1.2,
pl.col("category").str.to_uppercase(),
pl.col("date").dt.year().alias("year")
])
过滤:
df.filter(
(pl.col("price") < 100) &
(pl.col("status") == "active") |
(pl.col("category").is_in(["A", "B"]))
)
聚合与分组:
results = df.group_by("department").agg([
pl.col("salary").sum(),
pl.col("salary").max().alias("max_pay"),
pl.col("name").n_unique().alias("unique_employees"),
pl.col("salary").filter(pl.col("role") == "manager").mean().alias("manager_avg")
])
连接与拼接(支持 inner、left、outer、semi、anti、cross 等):
df_joined = df_a.join(df_b, on="id", how="left")
df_aligned = df_trades.join_asof(df_quotes, on="timestamp", by="symbol")
df_stacked = pl.concat([df1, df2], how="vertical")
重塑(透视与逆透视):
pivoted = df.pivot(values="sales", index="date", columns="region", aggregate_function="sum")
melted = df.melt(id_vars="date", value_vars=["store_a", "store_b"])
实践工作流
大规模数据清洗管道:
def clean_and_optimize(path):
return (
pl.scan_parquet(path)
.drop_nulls(subset=["user_id"])
.with_columns([
pl.col("email").str.to_lowercase(),
pl.col("timestamp").str.to_datetime("%Y-%m-%d %H:%M:%S"),
(pl.col("income") / 1000).cast(pl.Float32)
])
.filter(pl.col("timestamp") > pl.date(2023, 1, 1))
.collect(streaming=True)
)
时间序列特征工程:
def engineer_features(df):
return df.with_columns([
pl.col("price").rolling_mean(window_size="7d", by="date").alias("rolling_7d"),
pl.col("price").shift(1).alias("prev_price"),
pl.col("sales").cum_sum().over("category")
])
快速 JSON/日志解析:
def parse_logs(path):
return (
pl.scan_ndjson(path)
.select([
"level",
pl.col("message").str.extract(r"Error: (.*)", 1),
pl.col("metadata").struct.field("user_id")
])
.collect()
)
性能优化要点
- 使用 with_columns 一次并行计算多个列,而非逐列创建。
- 可通过 dtype 批量选择列,例如把所有 Float64 列乘 100。
- 低基数字符串(如 City、Gender)转换为 Categorical,可大幅节省内存并加快连接。
常见陷阱与解决
- .apply() 陷阱:map_elements()(原 .apply())中的 Python 函数很慢,应改用原生表达式或 pl.when()。
- 大文件内存错误:在惰性计划中尽早 filter、使用 collect(streaming=True)、只选择需要的列。
- 字符串与 Categorical:对低基数字符串使用 Categorical 以节省 RAM 并加速连接。
最佳实践
- 大文件始终用惰性 API,从 scan_csv() 或 scan_parquet() 开始。
- 在收集前构建完整查询计划,让 Polars 优化整个管道。
- 用表达式代替 Python 函数。
- 读取 CSV 时指定 schema。
- 内存不足的数据集启用 streaming=True。
- 优先使用 Parquet 格式。
- 低基数字符串转为 Categorical。
- 用 with_columns 做多个转换。
- 在惰性查询中尽早过滤,利用谓词下推减少扫描数据。
- 避免转换为 pandas。
资料称 Polars 是单节点数据处理的新标准,结合了 Rust 的安全性与 Python 的灵活性。以上为资料中提供的功能与用法说明,未提及收费、价格或商业授权等信息,暂未提供。