Path: blob/main/py-polars/tests/unit/lazyframe/test_rename.py
6939 views
from types import MappingProxyType12import pytest34import polars as pl5from polars.exceptions import ColumnNotFoundError6from polars.testing import assert_frame_equal789def test_lazy_rename() -> None:10lf = pl.LazyFrame({"x": [1], "y": [2]})1112result = lf.rename({"y": "x", "x": "y"}).select(["x", "y"]).collect()13assert result.to_dict(as_series=False) == {"x": [2], "y": [1]}1415# the `strict` param controls whether we fail on columns not found in the frame16remap_colnames = {"b": "a", "y": "x", "a": "b", "x": "y"}17with pytest.raises(ColumnNotFoundError, match='"b" not found'):18lf.rename(remap_colnames).collect()1920result = lf.rename(remap_colnames, strict=False).collect()21assert result.to_dict(as_series=False) == {"x": [2], "y": [1]}222324def test_remove_redundant_mapping_4668() -> None:25lf = pl.LazyFrame([["a"]] * 2, ["A", "B "]).lazy()26clean_name_dict = {x: " ".join(x.split()) for x in lf.collect_schema()}27lf = lf.rename(clean_name_dict)28assert lf.collect_schema().names() == ["A", "B"]293031def test_rename_mapping_19400() -> None:32# use a mapping type that is not a dict33mapping = MappingProxyType({"a": "b", "b": "c"})3435assert pl.LazyFrame({"a": [1], "b": [2]}).rename(mapping).collect().to_dict(36as_series=False37) == {"b": [1], "c": [2]}383940def test_rename_non_strict_20407() -> None:41assert_frame_equal(42pl.LazyFrame({"TEST": [1]})43.rename({"NOT FOUND": "TEST"}, strict=False)44.select("TEST")45.collect(),46pl.DataFrame({"TEST": [1]}),47)484950