Narwhals

From anam-org/metaxy · View interactive version

Narwhals is an AI agent skill from the GitHub repository anam-org/metaxy. Effectively use Narwhals to write dataframe-agnostic code that works seamlessly across multiple Python dataframe libraries. Write correct type annotations for code using Narwhals.

How to use this skill

Skill file

Narwhals - DataFrame Agnostic API

Narwhals is a lightweight, zero-dependency compatibility layer for dataframe libraries in Python that provides a unified interface across different backends.

Docs: https://narwhals-dev.github.io/narwhals/

What is Narwhals?

Narwhals enables writing dataframe-agnostic code that works seamlessly across multiple Python dataframe libraries:

Full API Support:

Lazy-Only Support:

Core Philosophy

Why Narwhals?

Target Use Case:

Anyone building libraries, applications, or services that consume dataframes and need complete backend independence.

Key Features

  1. Backend Agnostic: Write once, run on any supported dataframe library
  2. Polars-Like API: Uses a subset of the Polars API for consistency
  3. Lazy & Eager Execution: Separate APIs for both execution modes
  4. Expression Support: Full expression API for complex operations
  5. Type Safety: Perfect static typing support
  6. 100% Branch Coverage: Thoroughly tested

Basic Usage Pattern

Three-Step Workflow

import narwhals as nw

# 1. Convert to Narwhals
df_nw = nw.from_native(df)  # Works with pandas, Polars, PyArrow, etc.

# 2. Perform operations using Polars-like API
result = df_nw.select(a_sum=nw.col("a").sum(), a_mean=nw.col("a").mean(), b_std=nw.col("b").std())

# 3. Convert back to original library
result_native = result.to_native()

Using the @narwhalify Decorator

Simplifies function definitions for automatic conversion:

@nw.narwhalify
def my_func(df: IntoDataFrameT):
    return df.select(nw.col("a").sum(), nw.col("b").mean()).filter(nw.col("a") > 0)


# Automatically handles conversion to/from Narwhals
result = my_func(pandas_df)  # Works!
result = my_func(polars_df)  # Also works!

Top-Level Functions

Conversion Functions

Data Creation

File I/O

Eager Loading:

Lazy Loading:

Aggregation Functions

Expression Creation

Utilities

DataFrame Methods

Properties

Column Operations

Row Operations

Inspection

Transformations

Export

LazyFrame Methods

LazyFrame provides the same API as DataFrame but with lazy evaluation:

Key Differences

Common Methods

All DataFrame methods are available on LazyFrame:

Expression (Expr) API

Expressions are the building blocks for column operations.

Creation

nw.col("column_name")  # Reference column
nw.lit(42)  # Literal value

Filtering

Aggregations

Transformations

Mathematical:

Type/Value Operations:

Window Operations:

Ranking/Uniqueness:

Namespace Methods

Expressions have specialized namespaces for specific data types:

String Operations (Expr.str)

DateTime Operations (Expr.dt)

List Operations (Expr.list)

Categorical Operations (Expr.cat)

Struct Operations (Expr.struct)

Name Operations (Expr.name)

Series API

Series represents a single column:

Properties

Methods

Type Hints

Full docs: narwhals.typing

TLDR:

DataFrameT module-attribute

DataFrameT = TypeVar('DataFrameT', bound='DataFrame[Any]')

TypeVar bound to Narwhals DataFrame.

Use this if your function can accept a Narwhals DataFrame and returns a Narwhals DataFrame backed by the same backend.

Examples:

>>> import narwhals as nw
>>> from narwhals.typing import DataFrameT
>>> @nw.narwhalify
>>> def func(df: DataFrameT) -> DataFrameT:
...     return df.with_columns(c=df["a"] + 1)
Frame module-attribute

Frame: TypeAlias = Union["DataFrame[Any]", "LazyFrame[Any]"]

Narwhals DataFrame or Narwhals LazyFrame.

Use this if your function can work with either and your function doesn't care about its backend.

Examples:

>>> import narwhals as nw
>>> from narwhals.typing import Frame
>>> @nw.narwhalify
... def agnostic_columns(df: Frame) -> list[str]:
...     return df.columns
FrameT module-attribute

FrameT = TypeVar(

"FrameT", "DataFrame[Any]", "LazyFrame[Any]"

)

TypeVar bound to Narwhals DataFrame or Narwhals LazyFrame.

Use this if your function accepts either nw.DataFrame or nw.LazyFrame and returns an object of the same kind.

Examples:

>>> import narwhals as nw
>>> from narwhals.typing import FrameT
>>> @nw.narwhalify
... def agnostic_func(df: FrameT) -> FrameT:
...     return df.with_columns(c=nw.col("a") + 1)

IntoDataFrame module-attribute

IntoDataFrame: TypeAlias = NativeDataFrame

Anything which can be converted to a Narwhals DataFrame.

Use this if your function accepts a narwhalifiable object but doesn't care about its backend.

Examples:

>>> import narwhals as nw
>>> from narwhals.typing import IntoDataFrame
>>> def agnostic_shape(df_native: IntoDataFrame) -> tuple[int, int]:
...     df = nw.from_native(df_native, eager_only=True)
...     return df.shape

IntoDataFrameT module-attribute

IntoDataFrameT = TypeVar(

"IntoDataFrameT", bound=IntoDataFrame

)

TypeVar bound to object convertible to Narwhals DataFrame.

Use this if your function accepts an object which can be converted to nw.DataFrame and returns an object of the same class.

Examples:

>>> import narwhals as nw
>>> from narwhals.typing import IntoDataFrameT
>>> def agnostic_func(df_native: IntoDataFrameT) -> IntoDataFrameT:
...     df = nw.from_native(df_native, eager_only=True)
...     return df.with_columns(c=df["a"] + 1).to_native()

Common Patterns

Group By and Aggregate

result = df.group_by("category").agg(
    count=nw.col("id").count(),
    total=nw.col("amount").sum(),
    average=nw.col("amount").mean(),
)

Conditional Operations

result = df.with_columns(category=nw.when(nw.col("value") > 100).then(nw.lit("high")).otherwise(nw.lit("low")))

Joins

result = df1.join(
    df2,
    on="key_column",
    how="left",  # inner, left, outer, cross
)

Chain Operations

result = (
    df.filter(nw.col("status") == "active")
    .select("user_id", "amount")
    .group_by("user_id")
    .agg(total=nw.col("amount").sum())
    .sort("total", descending=True)
    .head(10)
)

Best Practices

  1. Use @nw.narwhalify for library functions: Simplifies API and handles conversion automatically
  1. Prefer expressions over method chaining: More flexible and composable

```python

# Good

df.select(nw.col("a").sum(), nw.col("b").mean())

# Also fine, but less composable

df.select("a", "b")

```

  1. Use lazy evaluation when possible: Better performance for complex pipelines

```python

result = df.lazy().select(...).filter(...).collect()

```

  1. Always convert back to native: Remember to call .to_native() when returning from library functions (unless using @narwhalify)
  1. Type hint your functions: Use IntoDataFrame and FrameT for better IDE support
  1. Check supported backends: Some operations may not be available on all backends

Important Constraints

  1. Zero Dependencies: Narwhals has no dependencies, keeping it lightweight
  1. Polars API Subset: Uses Polars-style API but may not support all Polars features
  1. Backend Limitations: Some backends (lazy-only) have restricted functionality

Tips

Checking whether a Narwhals frame is a Polars frame:

import polars as pl
import narwhals as nw

df_native = pl.DataFrame({"a": [1, 2, 3]})
df = nw.from_native(df_native)
df.implementation.is_polars()

Asserting series equality:

import pandas as pd
import narwhals as nw
from narwhals.testing import assert_series_equal
s1 = nw.from_native(pd.Series([1, 2, 3]), series_only=True)
s2 = nw.from_native(pd.Series([1, 5, 3]), series_only=True)
assert_series_equal(s1, s2)
Traceback (most recent call last):
...
AssertionError: Series are different (exact value mismatch)
[left]:
┌───────────────┐
|Narwhals Series|
|---------------|
| 0    1        |
| 1    2        |
| 2    3        |
| dtype: int64  |
└───────────────┘
[right]:
┌───────────────┐
|Narwhals Series|
|---------------|
| 0    1        |
| 1    5        |
| 2    3        |
| dtype: int64  |
└───────────────┘
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.