Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(python): allow df.rename and lf.rename to take a renaming function #13708

Merged
merged 4 commits into from
Jan 19, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions py-polars/polars/dataframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4058,14 +4058,14 @@ def reverse(self) -> DataFrame:
"""
return self.select(F.col("*").reverse())

def rename(self, mapping: dict[str, str]) -> DataFrame:
def rename(self, mapping: dict[str, str] | Callable[[str], str]) -> DataFrame:
"""
Rename column names.

Parameters
----------
mapping
Key value pairs that map from old name to new name.
Key value pairs that map from old name to new name, or a function.
alexander-beedie marked this conversation as resolved.
Show resolved Hide resolved

Examples
--------
Expand All @@ -4083,8 +4083,22 @@ def rename(self, mapping: dict[str, str]) -> DataFrame:
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└───────┴─────┴─────┘
>>> df.rename(lambda column_name: "c" + column_name[1:])
shape: (3, 3)
┌─────┬─────┬─────┐
│ coo ┆ car ┆ cam │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└─────┴─────┴─────┘
"""
return self.lazy().rename(mapping).collect(_eager=True)
if callable(mapping):
alexander-beedie marked this conversation as resolved.
Show resolved Hide resolved
return self.select(F.all().name.map(mapping))
else:
return self.lazy().rename(mapping).collect(_eager=True)

def insert_column(self, index: int, column: Series) -> Self:
"""
Expand Down
24 changes: 19 additions & 5 deletions py-polars/polars/lazyframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4165,14 +4165,14 @@ def drop(
drop_cols = _expand_selectors(self, *columns)
return self._from_pyldf(self._ldf.drop(drop_cols))

def rename(self, mapping: dict[str, str]) -> Self:
def rename(self, mapping: dict[str, str] | Callable[[str], str]) -> Self:
"""
Rename column names.

Parameters
----------
mapping
Key value pairs that map from old name to new name.
Key value pairs that map from old name to new name, or a function.

Notes
-----
Expand All @@ -4199,10 +4199,24 @@ def rename(self, mapping: dict[str, str]) -> Self:
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└───────┴─────┴─────┘
>>> lf.rename(lambda column_name: "c" + column_name[1:]).collect()
shape: (3, 3)
┌─────┬─────┬─────┐
│ coo ┆ car ┆ cam │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
└─────┴─────┴─────┘
"""
existing = list(mapping.keys())
new = list(mapping.values())
return self._from_pyldf(self._ldf.rename(existing, new))
if callable(mapping):
return self.select(F.all().name.map(mapping))
else:
existing = list(mapping.keys())
new = list(mapping.values())
return self._from_pyldf(self._ldf.rename(existing, new))

def reverse(self) -> Self:
"""
Expand Down
6 changes: 6 additions & 0 deletions py-polars/tests/unit/dataframe/test_df.py
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,12 @@ def test_rename(df: pl.DataFrame) -> None:
_ = out[["foos", "bars"]]


def test_rename_lambda() -> None:
df = pl.DataFrame({"a": [1], "b": [2], "c": [3]})
out = df.rename(lambda col: "foo" if col == "a" else "bar" if col == "b" else col)
assert out.columns == ["foo", "bar", "c"]


def test_write_csv() -> None:
df = pl.DataFrame(
{
Expand Down
8 changes: 8 additions & 0 deletions py-polars/tests/unit/test_lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,14 @@ def test_with_column_renamed(fruits_cars: pl.DataFrame) -> None:
assert res.columns[0] == "C"


def test_rename_lambda() -> None:
ldf = pl.LazyFrame({"a": [1], "b": [2], "c": [3]})
out = ldf.rename(
lambda col: "foo" if col == "a" else "bar" if col == "b" else col
).collect()
assert out.columns == ["foo", "bar", "c"]


def test_reverse() -> None:
out = pl.LazyFrame({"a": [1, 2], "b": [3, 4]}).reverse()
expected = pl.DataFrame({"a": [2, 1], "b": [4, 3]})
Expand Down