Path: blob/main/py-polars/tests/unit/test_pipe_with_schema.py
6939 views
import polars as pl123def test_pipe_with_schema() -> None:4def cast_to_float_if_necessary(lf: pl.LazyFrame, schema: pl.Schema) -> pl.LazyFrame:5required_casts = [6pl.col(name).cast(pl.Float64)7for name, dtype in schema.items()8if not dtype.is_float()9]10return lf.with_columns(required_casts)1112lf = pl.LazyFrame(13{"a": [1.0, 2.0], "b": ["1.0", "2.5"], "c": [2.0, 3.0]},14schema={"a": pl.Float64, "b": pl.String, "c": pl.Float32},15)16result = lf.pipe_with_schema(cast_to_float_if_necessary).collect()1718assert result.schema == {"a": pl.Float64, "b": pl.Float64, "c": pl.Float32}192021def test_pipe_with_schema_rewrite() -> None:22def rewrite(lf: pl.LazyFrame, schema: pl.Schema) -> pl.LazyFrame:23return pl.LazyFrame({"x": [1, 2, 3]})2425lf = pl.LazyFrame({"a": [1, 2]})26result = lf.pipe_with_schema(rewrite).collect()2728assert result.schema == {"x": pl.Int64}29assert result.height == 3303132