⌘+k ctrl+k
1.3 (稳定版)
搜索快捷键 cmd + k | ctrl + k
与 Polars 集成

Polars 是一个使用 Rust 构建的 DataFrame 库,提供 Python 和 Node.js 绑定。它使用 Apache Arrow 的列式格式 作为其内存模型。DuckDB 可以读取 Polars DataFrame 并将查询结果转换为 Polars DataFrame。它通过高效的 Apache Arrow 集成在内部完成此操作。请注意,要使此集成正常工作,必须安装 pyarrow 库。

安装

pip install -U duckdb 'polars[pyarrow]'

Polars 到 DuckDB

DuckDB 可以通过引用当前作用域中存在的 Polars DataFrame 的名称来原生查询 Polars DataFrame。

import duckdb
import polars as pl

df = pl.DataFrame(
    {
        "A": [1, 2, 3, 4, 5],
        "fruits": ["banana", "banana", "apple", "apple", "banana"],
        "B": [5, 4, 3, 2, 1],
        "cars": ["beetle", "audi", "beetle", "beetle", "beetle"],
    }
)
duckdb.sql("SELECT * FROM df").show()

DuckDB 到 Polars

DuckDB 可以使用 .pl() 结果转换方法将结果输出为 Polars DataFrame。

df = duckdb.sql("""
    SELECT 1 AS id, 'banana' AS fruit
    UNION ALL
    SELECT 2, 'apple'
    UNION ALL
    SELECT 3, 'mango'"""
).pl()
print(df)
shape: (3, 2)
┌─────┬────────┐
│ id  ┆ fruit  │
│ --- ┆ ---    │
│ i32 ┆ str    │
╞═════╪════════╡
│ 1   ┆ banana │
│ 2   ┆ apple  │
│ 3   ┆ mango  │
└─────┴────────┘

要了解有关 Polars 的更多信息,请随时查阅其 Python API 参考