模式#

class polars.Schema(
schema: Mapping[str, SchemaInitDataType] | Iterable[tuple[str, SchemaInitDataType]] | None = None,
*,
check_dtypes: bool = True,
)[source]

列名到其数据类型的顺序映射。

Parameters:
schema

由列名及其关联的Polars数据类型给出的模式定义。接受映射或元组的可迭代对象。

示例

通过传递实例化的数据类型来定义一个模式。

>>> schema = pl.Schema(
...     {
...         "foo": pl.String(),
...         "bar": pl.Duration("us"),
...         "baz": pl.Array(pl.Int8, 4),
...     }
... )
>>> schema
Schema({'foo': String, 'bar': Duration(time_unit='us'), 'baz': Array(Int8, shape=(4,))})

访问与特定列名关联的数据类型。

>>> schema["baz"]
Array(Int8, shape=(4,))

使用namesdtypeslen方法访问各种模式属性。

>>> schema.names()
['foo', 'bar', 'baz']
>>> schema.dtypes()
[String, Duration(time_unit='us'), Array(Int8, shape=(4,))]
>>> schema.len()
3

方法:

dtypes

获取模式的数据类型。

len

获取模式条目的数量。

names

获取模式的列名。

to_frame

从这个Schema创建一个空的DataFrame(或LazyFrame)。

to_python

返回列名和Python类型的字典。

dtypes() list[DataType][source]

获取模式的数据类型。

示例

>>> s = pl.Schema({"x": pl.UInt8(), "y": pl.List(pl.UInt8)})
>>> s.dtypes()
[UInt8, List(UInt8)]
len() int[source]

获取模式条目的数量。

示例

>>> s = pl.Schema({"x": pl.Int32(), "y": pl.List(pl.String)})
>>> s.len()
2
>>> len(s)
2
names() list[str][source]

获取模式的列名。

示例

>>> s = pl.Schema({"x": pl.Float64(), "y": pl.Datetime(time_zone="UTC")})
>>> s.names()
['x', 'y']
to_frame(*, eager: bool = True) DataFrame | LazyFrame[source]

从这个Schema创建一个空的DataFrame(或LazyFrame)。

Parameters:
eager

如果为True,则创建一个DataFrame;否则,创建一个LazyFrame。

示例

>>> s = pl.Schema({"x": pl.Int32(), "y": pl.String()})
>>> s.to_frame()
shape: (0, 2)
┌─────┬─────┐
│ x   ┆ y   │
│ --- ┆ --- │
│ i32 ┆ str │
╞═════╪═════╡
└─────┴─────┘
>>> s.to_frame(eager=False)  
<LazyFrame at 0x11BC0AD80>
to_python() dict[str, type][source]

返回列名和Python类型的字典。

示例

>>> s = pl.Schema(
...     {
...         "x": pl.Int8(),
...         "y": pl.String(),
...         "z": pl.Duration("us"),
...     }
... )
>>> s.to_python()
{'x': <class 'int'>, 'y':  <class 'str'>, 'z': <class 'datetime.timedelta'>}