Skip to content

Commit 6db95e7

Browse files
authored
ENH: copy kwd for add_suffix/add_prefix (#47934)
* ENH: copy kwd for add_suffix/add_prefix * GH ref * test series
1 parent 9a88d42 commit 6db95e7

File tree

3 files changed

+66
-4
lines changed

3 files changed

+66
-4
lines changed

doc/source/whatsnew/v1.5.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,7 @@ Other enhancements
292292
- :class:`Series` reducers (e.g. ``min``, ``max``, ``sum``, ``mean``) will now successfully operate when the dtype is numeric and ``numeric_only=True`` is provided; previously this would raise a ``NotImplementedError`` (:issue:`47500`)
293293
- :meth:`RangeIndex.union` now can return a :class:`RangeIndex` instead of a :class:`Int64Index` if the resulting values are equally spaced (:issue:`47557`, :issue:`43885`)
294294
- :meth:`DataFrame.compare` now accepts an argument ``result_names`` to allow the user to specify the result's names of both left and right DataFrame which are being compared. This is by default ``'self'`` and ``'other'`` (:issue:`44354`)
295+
- :meth:`Series.add_suffix`, :meth:`DataFrame.add_suffix`, :meth:`Series.add_prefix` and :meth:`DataFrame.add_prefix` support a ``copy`` argument. If ``False``, the underlying data is not copied in the returned object (:issue:`47934`)
295296

296297
.. ---------------------------------------------------------------------------
297298
.. _whatsnew_150.notable_bug_fixes:

pandas/core/generic.py

+12-4
Original file line numberDiff line numberDiff line change
@@ -4549,7 +4549,7 @@ def _update_inplace(self, result, verify_is_copy: bool_t = True) -> None:
45494549
self._maybe_update_cacher(verify_is_copy=verify_is_copy, inplace=True)
45504550

45514551
@final
4552-
def add_prefix(self: NDFrameT, prefix: str) -> NDFrameT:
4552+
def add_prefix(self: NDFrameT, prefix: str, copy: bool_t = True) -> NDFrameT:
45534553
"""
45544554
Prefix labels with string `prefix`.
45554555
@@ -4560,6 +4560,10 @@ def add_prefix(self: NDFrameT, prefix: str) -> NDFrameT:
45604560
----------
45614561
prefix : str
45624562
The string to add before each label.
4563+
copy : bool, default True
4564+
Whether to copy the underlying data.
4565+
4566+
.. versionadded:: 1.5.0
45634567
45644568
Returns
45654569
-------
@@ -4610,10 +4614,10 @@ def add_prefix(self: NDFrameT, prefix: str) -> NDFrameT:
46104614
# expected "NDFrameT")
46114615
# error: Argument 1 to "rename" of "NDFrame" has incompatible type
46124616
# "**Dict[str, partial[str]]"; expected "Union[str, int, None]"
4613-
return self._rename(**mapper) # type: ignore[return-value, arg-type]
4617+
return self._rename(**mapper, copy=copy) # type: ignore[return-value, arg-type]
46144618

46154619
@final
4616-
def add_suffix(self: NDFrameT, suffix: str) -> NDFrameT:
4620+
def add_suffix(self: NDFrameT, suffix: str, copy: bool_t = True) -> NDFrameT:
46174621
"""
46184622
Suffix labels with string `suffix`.
46194623
@@ -4624,6 +4628,10 @@ def add_suffix(self: NDFrameT, suffix: str) -> NDFrameT:
46244628
----------
46254629
suffix : str
46264630
The string to add after each label.
4631+
copy : bool, default True
4632+
Whether to copy the underlying data.
4633+
4634+
.. versionadded:: 1.5.0
46274635
46284636
Returns
46294637
-------
@@ -4674,7 +4682,7 @@ def add_suffix(self: NDFrameT, suffix: str) -> NDFrameT:
46744682
# expected "NDFrameT")
46754683
# error: Argument 1 to "rename" of "NDFrame" has incompatible type
46764684
# "**Dict[str, partial[str]]"; expected "Union[str, int, None]"
4677-
return self._rename(**mapper) # type: ignore[return-value, arg-type]
4685+
return self._rename(**mapper, copy=copy) # type: ignore[return-value, arg-type]
46784686

46794687
@overload
46804688
def sort_values(

pandas/tests/frame/methods/test_add_prefix_suffix.py

+53
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,56 @@ def test_add_prefix_suffix(float_frame):
1818
with_pct_suffix = float_frame.add_suffix("%")
1919
expected = Index([f"{c}%" for c in float_frame.columns])
2020
tm.assert_index_equal(with_pct_suffix.columns, expected)
21+
22+
23+
def test_add_prefix_suffix_copy(float_frame):
24+
# GH#47934
25+
ser = float_frame.iloc[0]
26+
27+
with_prefix = float_frame.add_prefix("foo#", copy=True)
28+
expected = Index([f"foo#{c}" for c in float_frame.columns])
29+
tm.assert_index_equal(with_prefix.columns, expected)
30+
assert not any(
31+
tm.shares_memory(float_frame.iloc[:, i], with_prefix.iloc[:, i])
32+
for i in range(float_frame.shape[1])
33+
)
34+
35+
ser_with_prefix = ser.add_prefix("foo#", copy=True)
36+
tm.assert_index_equal(ser_with_prefix.index, expected)
37+
assert not tm.shares_memory(ser_with_prefix, ser)
38+
39+
with_prefix = float_frame.add_prefix("foo#", copy=False)
40+
expected = Index([f"foo#{c}" for c in float_frame.columns])
41+
tm.assert_index_equal(with_prefix.columns, expected)
42+
assert all(
43+
tm.shares_memory(float_frame.iloc[:, i], with_prefix.iloc[:, i])
44+
for i in range(float_frame.shape[1])
45+
)
46+
47+
ser_with_prefix = ser.add_prefix("foo#", copy=False)
48+
tm.assert_index_equal(ser_with_prefix.index, expected)
49+
assert tm.shares_memory(ser_with_prefix, ser)
50+
51+
with_suffix = float_frame.add_suffix("#foo", copy=True)
52+
expected = Index([f"{c}#foo" for c in float_frame.columns])
53+
tm.assert_index_equal(with_suffix.columns, expected)
54+
assert not any(
55+
tm.shares_memory(float_frame.iloc[:, i], with_suffix.iloc[:, i])
56+
for i in range(float_frame.shape[1])
57+
)
58+
59+
ser_with_suffix = ser.add_suffix("#foo", copy=True)
60+
tm.assert_index_equal(ser_with_suffix.index, expected)
61+
assert not tm.shares_memory(ser_with_suffix, ser)
62+
63+
with_suffix = float_frame.add_suffix("#foo", copy=False)
64+
expected = Index([f"{c}#foo" for c in float_frame.columns])
65+
tm.assert_index_equal(with_suffix.columns, expected)
66+
assert all(
67+
tm.shares_memory(float_frame.iloc[:, i], with_suffix.iloc[:, i])
68+
for i in range(float_frame.shape[1])
69+
)
70+
71+
ser_with_suffix = ser.add_suffix("#foo", copy=False)
72+
tm.assert_index_equal(ser_with_suffix.index, expected)
73+
assert tm.shares_memory(ser_with_suffix, ser)

0 commit comments

Comments
 (0)