Skip to content

BUG: Series.rename(scalar, copy=False) still copies data #52450

Closed
@kandersolar

Description

@kandersolar

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd

s1 = pd.Series([1])
s2 = s1.rename(None, copy=False)
s2.loc[:] = 100
print(s1)  # original series not modified

Issue Description

Series.rename does not consider the copy kwarg when passing scalar index:

pandas/pandas/core/series.py

Lines 4848 to 4865 in 478d340

if axis is not None:
# Make sure we raise if an invalid 'axis' is passed.
axis = self._get_axis_number(axis)
if callable(index) or is_dict_like(index):
# error: Argument 1 to "_rename" of "NDFrame" has incompatible
# type "Union[Union[Mapping[Any, Hashable], Callable[[Any],
# Hashable]], Hashable, None]"; expected "Union[Mapping[Any,
# Hashable], Callable[[Any], Hashable], None]"
return super()._rename(
index, # type: ignore[arg-type]
copy=copy,
inplace=inplace,
level=level,
errors=errors,
)
else:
return self._set_name(index, inplace=inplace)

If inplace=False, the call to self._set_name eventually leads to a call to self.copy() which leaves the default deep=True, meaning the data gets copied.

Expected Behavior

I expect setting copy=False to prevent data from being copied regardless of which branch in Series.rename is taken.

Installed Versions

The versions below are with pandas 2.0.0, but I observe this issue in 1.x as well.

INSTALLED VERSIONS

commit : 478d340
python : 3.9.12.final.0
python-bits : 64
OS : Linux
OS-release : 6.1.11-76060111-generic
Version : #202302091138167597574922.04~f771a7f SMP PREEMPT_DYNAMIC Thu F
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 2.0.0
numpy : 1.22.4
pytz : 2022.1
dateutil : 2.8.2
setuptools : 61.2.0
pip : 22.1.2
Cython : 0.29.30
pytest : 7.1.2
hypothesis : None
sphinx : 4.5.0
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.3
IPython : 8.4.0
pandas_datareader: None
bs4 : 4.11.1
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.5.2
numba : 0.55.2
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.8.1
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions