Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/py-polars/tests/unit/test_pipe_with_schema.py
6939 views
1
import polars as pl
2
3
4
def test_pipe_with_schema() -> None:
5
def cast_to_float_if_necessary(lf: pl.LazyFrame, schema: pl.Schema) -> pl.LazyFrame:
6
required_casts = [
7
pl.col(name).cast(pl.Float64)
8
for name, dtype in schema.items()
9
if not dtype.is_float()
10
]
11
return lf.with_columns(required_casts)
12
13
lf = pl.LazyFrame(
14
{"a": [1.0, 2.0], "b": ["1.0", "2.5"], "c": [2.0, 3.0]},
15
schema={"a": pl.Float64, "b": pl.String, "c": pl.Float32},
16
)
17
result = lf.pipe_with_schema(cast_to_float_if_necessary).collect()
18
19
assert result.schema == {"a": pl.Float64, "b": pl.Float64, "c": pl.Float32}
20
21
22
def test_pipe_with_schema_rewrite() -> None:
23
def rewrite(lf: pl.LazyFrame, schema: pl.Schema) -> pl.LazyFrame:
24
return pl.LazyFrame({"x": [1, 2, 3]})
25
26
lf = pl.LazyFrame({"a": [1, 2]})
27
result = lf.pipe_with_schema(rewrite).collect()
28
29
assert result.schema == {"x": pl.Int64}
30
assert result.height == 3
31
32