Skip to content

Commit 9573aa1

Browse files
committed
Add inplace support for rename_axis and add tests for happy case
1 parent 03d44f3 commit 9573aa1

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
lines changed

pandas/core/generic.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -753,7 +753,7 @@ def rename_axis(self, mapper, axis=0, copy=True, inplace=False):
753753
754754
Returns
755755
-------
756-
renamed : type of caller
756+
renamed : type of caller or None if inplace=True
757757
758758
See Also
759759
--------
@@ -784,27 +784,29 @@ def rename_axis(self, mapper, axis=0, copy=True, inplace=False):
784784
non_mapper = is_scalar(mapper) or (is_list_like(mapper) and not
785785
is_dict_like(mapper))
786786
if non_mapper:
787-
return self._set_axis_name(mapper, axis=axis)
787+
return self._set_axis_name(mapper, axis=axis, inplace=inplace)
788788
else:
789789
axis = self._get_axis_name(axis)
790790
d = {'copy': copy, 'inplace': inplace}
791791
d[axis] = mapper
792792
return self.rename(**d)
793793

794-
def _set_axis_name(self, name, axis=0):
794+
def _set_axis_name(self, name, axis=0, inplace=False):
795795
"""
796-
Alter the name or names of the axis, returning self.
796+
Alter the name or names of the axis.
797797
798798
Parameters
799799
----------
800800
name : str or list of str
801801
Name for the Index, or list of names for the MultiIndex
802802
axis : int or str
803803
0 or 'index' for the index; 1 or 'columns' for the columns
804+
inplace : bool
805+
whether to modify `self` directly or return a copy
804806
805807
Returns
806808
-------
807-
renamed : type of caller
809+
renamed : type of caller or None if inplace=True
808810
809811
See Also
810812
--------
@@ -831,9 +833,11 @@ def _set_axis_name(self, name, axis=0):
831833
axis = self._get_axis_number(axis)
832834
idx = self._get_axis(axis).set_names(name)
833835

834-
renamed = self.copy(deep=True)
836+
inplace = validate_bool_kwarg(inplace, 'inplace')
837+
renamed = self if inplace else self.copy(deep=True)
835838
renamed.set_axis(axis, idx)
836-
return renamed
839+
if not inplace:
840+
return renamed
837841

838842
# ----------------------------------------------------------------------
839843
# Comparisons

pandas/tests/frame/test_alter_axes.py

+7
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,13 @@ def test_rename(self):
418418
pd.Index(['bar', 'foo'], name='name'))
419419
assert renamed.index.name == renamer.index.name
420420

421+
def test_rename_axis(self):
422+
renamed = self.frame.rename_axis('foo')
423+
no_return = self.frame.rename_axis('foo', inplace=True)
424+
assert no_return is None
425+
renamed2 = self.frame
426+
assert_frame_equal(renamed, renamed2)
427+
421428
def test_rename_multiindex(self):
422429

423430
tuples_index = [('foo1', 'bar1'), ('foo2', 'bar2')]

0 commit comments

Comments
 (0)