narwhals
БесплатноБез исполняемых скриптовНе проверенEffectively use Narwhals to write dataframe-agnostic code that works seamlessly across multiple Python dataframe libraries. Write correct type annotations for…
Об этом скилле
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:
- cuDF
- Modin
- pandas
- Polars
- PyArrow
Lazy-Only Support:
- Dask
- DuckDB
- Ibis
- PySpark
- SQLFrame
Core Philosophy
Why Narwhals?
- Resolves subtle differences between libraries (e.g., pandas checking index vs Polars checking values)
- Provides unified, simple, and predictable API
- Handles backwards compatibility internally
- Tests against nightly builds of supported libraries
- Maintains negligible performance overhead
- Full static typing support
- Zero dependencies
Target Use Case: Anyone building libraries, applications, or services that consume dataframes and need complete backend independence.
Key Features
- Backend Agnostic: Write once, run on any supported dataframe library
- Polars-Like API: Uses a subset of the Polars API for consistency
- Lazy & Eager Execution: Separate APIs for both execution modes
- Expression Support: Full expression API for complex operations
- Type Safety: Perfect static typing support
- 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
from_native(df, ...): Convert native DataFrame/Series to Narwhals object- Parameters:
pass_through,backend,eager_only,allow_series
- Parameters:
to_native(nw_obj): Convert Narwhals object back to native library typenarwhalify(): Decorator for automatic dataframe-agnostic functions
Data Creation
new_series(name, values, dtype): Create a new Seriesfrom_dict(data): Create DataFrame from dictionaryfrom_dicts(data): Create DataFrame from sequence of dictionaries
File I/O
Eager Loading:
read_csv(source, **kwargs): Read CSV file into DataFrameread_parquet(source, **kwargs): Read Parquet file into DataFrame
Lazy Loading:
scan_csv(source, **kwargs): Lazily scan CSV filescan_parquet(source, **kwargs): Lazily scan Parquet file
Aggregation Functions
sum(),mean(),min(),max(),median()sum_horizontal(),mean_horizontal(), etc.
Expression Creation
col(name): Reference column by namelit(value): Create literal expressionwhen(condition): Create conditional expressionformat(template, *args): Format expression as string
Utilities
generate_temporary_column_name(): Generate unique column namesget_native_namespace(obj): Get the native library of an objectshow_versions(): Print debugging information
DataFrame Methods
Properties
columns: List of column namesschema: Ordered mapping of column names to dtypesshape: Tuple of (rows, columns)implementation: Name of native implementation
Column Operations
select(*exprs): Select columns using expressionswith_columns(*exprs): Add or modify columnsdrop(*columns): Remove specified columnsrename(mapping): Rename columns
Row Operations
filter(predicate): Filter rows based on conditionshead(n): Get first n rowstail(n): Get last n rowssample(n): Randomly sample n rowsdrop_nulls(): Drop rows with null valuesunique(): Remove duplicate rows
Inspection
is_empty(): Check if DataFrame has no rowsis_duplicated(): Identify duplicated rowsis_unique(): Identify unique rowsnull_count(): Count null values per columnestimated_size(): Estimate memory usage
Transformations
sort(*by): Sort by one or more columnsgroup_by(*by): Group by columns for aggregationjoin(other, on, how): Perform SQL-style joinspivot(on, index, values): Create pivot tableexplode(*columns): Expand list columns to long formatlazy(): Convert to LazyFrame
Export
to_native(): Convert to original library typeto_numpy(): Convert to NumPy arrayto_pandas(): Convert to pandas DataFrameto_polars(): Convert
Установить narwhals в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл narwhals?
Effectively use Narwhals to write dataframe-agnostic code that works seamlessly across multiple Python dataframe libraries. Write correct type annotations for code using Narwhals.
Как установить скилл narwhals?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл narwhals запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic