Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/py-polars/tests/unit/lazyframe/test_rename.py
6939 views
1
from types import MappingProxyType
2
3
import pytest
4
5
import polars as pl
6
from polars.exceptions import ColumnNotFoundError
7
from polars.testing import assert_frame_equal
8
9
10
def test_lazy_rename() -> None:
11
lf = pl.LazyFrame({"x": [1], "y": [2]})
12
13
result = lf.rename({"y": "x", "x": "y"}).select(["x", "y"]).collect()
14
assert result.to_dict(as_series=False) == {"x": [2], "y": [1]}
15
16
# the `strict` param controls whether we fail on columns not found in the frame
17
remap_colnames = {"b": "a", "y": "x", "a": "b", "x": "y"}
18
with pytest.raises(ColumnNotFoundError, match='"b" not found'):
19
lf.rename(remap_colnames).collect()
20
21
result = lf.rename(remap_colnames, strict=False).collect()
22
assert result.to_dict(as_series=False) == {"x": [2], "y": [1]}
23
24
25
def test_remove_redundant_mapping_4668() -> None:
26
lf = pl.LazyFrame([["a"]] * 2, ["A", "B "]).lazy()
27
clean_name_dict = {x: " ".join(x.split()) for x in lf.collect_schema()}
28
lf = lf.rename(clean_name_dict)
29
assert lf.collect_schema().names() == ["A", "B"]
30
31
32
def test_rename_mapping_19400() -> None:
33
# use a mapping type that is not a dict
34
mapping = MappingProxyType({"a": "b", "b": "c"})
35
36
assert pl.LazyFrame({"a": [1], "b": [2]}).rename(mapping).collect().to_dict(
37
as_series=False
38
) == {"b": [1], "c": [2]}
39
40
41
def test_rename_non_strict_20407() -> None:
42
assert_frame_equal(
43
pl.LazyFrame({"TEST": [1]})
44
.rename({"NOT FOUND": "TEST"}, strict=False)
45
.select("TEST")
46
.collect(),
47
pl.DataFrame({"TEST": [1]}),
48
)
49
50