Skip to content

Commit cfeac25

Browse files
committed
perf: Use rename instead of with_columns
- Seems to be the most minimal change to resolve (#2680 (comment)) - Need to review what else is still needed
1 parent 5fd4160 commit cfeac25

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

narwhals/_pandas_like/dataframe.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -460,9 +460,11 @@ def with_columns(self, *exprs: PandasLikeExpr) -> Self:
460460
return self._with_native(df, validate_column_names=False)
461461

462462
def rename(self, mapping: Mapping[str, str]) -> Self:
463-
return self._with_native(
464-
rename(self.native, columns=mapping, implementation=self._implementation)
465-
)
463+
if mapping:
464+
return self._with_native(
465+
rename(self.native, columns=mapping, implementation=self._implementation)
466+
)
467+
return self._with_native(self.native, validate_column_names=False)
466468

467469
def drop(self, columns: Sequence[str], *, strict: bool) -> Self:
468470
to_drop = parse_columns_to_drop(self, columns, strict=strict)

narwhals/_pandas_like/group_by.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -160,11 +160,12 @@ def named_aggs(
160160
self, group_by: PandasLikeGroupBy, /
161161
) -> Iterator[tuple[str, _NamedAgg]]:
162162
aliases = collect(group_by._aliases_str(self.aliases))
163+
output_names = collect(group_by._aliases_str(self.output_names))
163164
native_agg = self.native_agg()
164165
if self.is_len() and self.is_anonymous():
165166
yield aliases[0], (group_by._anonymous_column_name, native_agg)
166167
return
167-
for output_name, alias in zip(self.output_names, aliases):
168+
for output_name, alias in zip(output_names, aliases):
168169
yield alias, (output_name, native_agg)
169170

170171
def _cast_coerced(self, group_by: PandasLikeGroupBy, /) -> Iterator[PandasLikeExpr]:
@@ -251,13 +252,10 @@ def __init__(
251252
) -> None:
252253
self._original_columns = tuple(df.columns)
253254
self._drop_null_keys = drop_null_keys
254-
ns = df.__narwhals_namespace__()
255255
frame, self._keys, self._output_key_names = self._parse_keys(df, keys=keys)
256256
self._exclude: tuple[str, ...] = (*self._keys, *self._output_key_names)
257257
self._remap_non_str_columns = _remap_non_str(self)
258-
self._compliant_frame = frame.with_columns(
259-
*(ns.col(old).alias(new) for old, new in self._remap_non_str_columns.items())
260-
)
258+
self._compliant_frame = frame.rename(self._remap_non_str_columns)
261259
# Drop index to avoid potential collisions:
262260
# https://github.com/narwhals-dev/narwhals/issues/1907.
263261
native = self.compliant.native

0 commit comments

Comments
 (0)