narwhals.Schema
Ordered mapping of column names to their data type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
Mapping[str, DType] | Iterable[tuple[str, DType]] | None
|
Mapping[str, DType] | Iterable[tuple[str, DType]] | None The schema definition given by column names and their associated. instantiated Narwhals data type. Accepts a mapping or an iterable of tuples. |
None
|
Examples:
Define a schema by passing instantiated data types.
>>> import narwhals as nw
>>> schema = nw.Schema({"foo": nw.Int8(), "bar": nw.String()})
>>> schema
Schema({'foo': Int8, 'bar': String})
Access the data type associated with a specific column name.
>>> schema["foo"]
Int8
Access various schema properties using the names
, dtypes
, and len
methods.
>>> schema.names()
['foo', 'bar']
>>> schema.dtypes()
[Int8, String]
>>> schema.len()
2
names() -> list[str]
Get the column names of the schema.
Returns:
Type | Description |
---|---|
list[str]
|
Column names. |
dtypes() -> list[DType]
Get the data types of the schema.
Returns:
Type | Description |
---|---|
list[DType]
|
Data types of schema. |
len() -> int
Get the number of columns in the schema.
Returns:
Type | Description |
---|---|
int
|
Number of columns. |
to_arrow() -> pa.Schema
Convert Schema to a pyarrow Schema.
Returns:
Type | Description |
---|---|
Schema
|
A pyarrow Schema. |
Examples:
>>> import narwhals as nw
>>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")})
>>> schema.to_arrow()
a: int64
b: timestamp[ns]
to_pandas(dtype_backend: DTypeBackend | Iterable[DTypeBackend] = None) -> dict[str, Any]
Convert Schema to an ordered mapping of column names to their pandas data type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dtype_backend
|
DTypeBackend | Iterable[DTypeBackend]
|
Backend(s) used for the native types. When providing more than one, the length of the iterable must be equal to the length of the schema. |
None
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
An ordered mapping of column names to their pandas data type. |
Examples:
>>> import narwhals as nw
>>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")})
>>> schema.to_pandas()
{'a': 'int64', 'b': 'datetime64[ns]'}
>>> schema.to_pandas("pyarrow")
{'a': 'Int64[pyarrow]', 'b': 'timestamp[ns][pyarrow]'}
to_polars() -> pl.Schema
Convert Schema to a polars Schema.
Returns:
Type | Description |
---|---|
Schema
|
A polars Schema or plain dict (prior to polars 1.0). |
Examples:
>>> import narwhals as nw
>>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")})
>>> schema.to_polars()
Schema({'a': Int64, 'b': Datetime(time_unit='ns', time_zone=None)})