Narwhals:DataFrame 库的轻量兼容层

Narwhals:DataFrame 库的轻量兼容层

Narwhals 是一个 Python DataFrame 兼容层,目前已获得 1,626 个 Star:

Narwhals 的定位是在多个 DataFrame 库之间提供统一的 API 调用方式。开发者写一次代码,就能在 pandas、Polars、DuckDB、PyArrow 等库之间切换。

目前 Narwhals 完整支持 cuDF、Modin、pandas、Polars 和 PyArrow。对 Daft、Dask、DuckDB、Ibis、PySpark 和 SQLFrame 提供 Lazy 模式支持。

Narwhals 的核心特点如下:

  • 使用 Polars API 的子集,不需要学习新的接口
  • 零依赖,只使用用户传入的库,不会增加项目体积
  • 区分 eager 和 lazy 两种 API,支持表达式
  • 兼容 pandas 的类型系统和索引,不会干扰原有逻辑
  • 100% 分支覆盖率,每天针对 pandas 和 Polars 的 nightly 版本进行测试
  • 开销极低,几乎不会带来性能损耗
  • 完整的静态类型支持,IDE 可以给出准确提示
  • 向后兼容策略明确,提供 stable API 供选择

安装很简单,通过 pip 直接安装:

nginx 复制代码
pip install narwhals

也可以使用 conda:

nginx 复制代码
conda install -c conda-forge narwhals

使用 Narwhals 只需要三个步骤。先用 narwhals.from_native 把 pandas、Polars 等 DataFrame 包装成 Narwhals 对象。然后调用 Narwhals 支持的 Polars API 子集进行数据处理。最后用 narwhals.to_native 把结果转回原始的 DataFrame 类型。

以下是一个完整的示例:

python 复制代码
import narwhals as nw
from narwhals.typing import IntoFrameT


def agnostic_function(df_native: IntoFrameT) -> IntoFrameT:
    return (
        nw.from_native(df_native)
        .with_columns(
            category=nw.when(nw.col("animal").str.contains("whale"))
            .then(nw.lit("whale"))
            .otherwise(nw.lit("other"))
        )
        .to_native()
    )

这个函数可以同时接受 pandas.DataFrame、polars.DataFrame、duckdb.DuckDBPyRelation 等多种类型。计算过程始终在原库内完成,不需要额外的依赖。

python 复制代码
import duckdb
import polars as pl
import pandas as pd

data = {
    "animal": ["blue whale", "orca", "dolphin", "humpback whale", "seal"],
    "length_m": [30.0, 8, 2.5, 17, 2.2],
    "weight_kg": [150000, 4000, 200, 30000, 85],
}

df_pl = pl.DataFrame(data)
print(agnostic_function(df_pl))

df_pd = pd.DataFrame(data)
print(agnostic_function(df_pd))

输出结果保持各库原生格式。Polars 返回 Polars 的 DataFrame,pandas 返回 pandas 的 DataFrame。

这个项目已经被 altair、bokeh、plotly、marimo 等多个库采用。如果你正在维护一个需要兼容多种 DataFrame 后端的 Python 库,Narwhals 是一个值得考虑的方案。

相关推荐
峰向AI6 小时前
学生党/打工人必备:AI自动把课程视频变成讲义
github
其实防守也摸鱼9 小时前
教育信息技术应用创新---基础软件信息赛
运维·服务器·数据库·github·copilot
0xR3lativ1ty12 小时前
AI本地部署工具火热趋势
github
LlmCraft|大模型工程实践14 小时前
14. CI/CD 流水线中集成 Docker:GitHub Actions 自动构建部署
ci/cd·docker·github
hulihutu4414 小时前
拒绝延期、bug、货不对板:2026 管理系统定制开发落地保障手册
github·bug·鸿蒙系统·数据库管理员
隔窗听雨眠14 小时前
活动中台系统慢SQL治理实践:从监控告警到性能优化的全链路方法论
sql·性能优化·github
m4Rk_15 小时前
【论文阅读】Agent 记忆机制(60):MemInsight——让 LLM 自动为历史记忆生成语义索引
论文阅读·人工智能·学习·开源·github
小弥儿20 小时前
开源 VoiceStudio,声音克隆|配音|有声书一站式本地完成
学习·开源·github
问天_观心1 天前
大模型微调学习(一)
开发语言·人工智能·学习·语言模型·github
峰向AI1 天前
SRT 白板动画:让字幕「画」出故事
github