8000 ENH: Allow rename_axis to specify index and columns arguments by Dr-Irv · Pull Request #20046 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

ENH: Allow rename_axis to specify index and columns arguments #20046

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

Merged
merged 19 commits into from
Oct 29, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
First version
  • Loading branch information
Dr-Irv committed Mar 7, 2018
commit bb12644328b3c58be26549f54a4ad15e4b0e58f6
49 changes: 27 additions & 22 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,20 @@ def swaplevel(self, i=-2, j=-1, axis=0):

# ----------------------------------------------------------------------
# Rename

# renamer function if passed a dict
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know you just moved the function, but let's take this opportunity to write a brief docstring.

def _get_rename_function(mapper):
if isinstance(mapper, (dict, ABCSeries)):

def f(x):
if x in mapper:
return mapper[x]
else:
return x
else:
f = mapper

return f

# TODO: define separate funcs for DataFrame, Series and Panel so you can
# get completion on keyword arguments.
Expand Down Expand Up @@ -874,20 +888,6 @@ def rename(self, *args, **kwargs):
if com._count_not_none(*axes.values()) == 0:
raise TypeError('must pass an index to rename')

# renamer function if passed a dict
def _get_rename_function(mapper):
if isinstance(mapper, (dict, ABCSeries)):

def f(x):
if x in mapper:
return mapper[x]
else:
return x
else:
f = mapper

return f

self._consolidate_inplace()
result = self if inplace else self.copy(deep=copy)

Expand All @@ -896,7 +896,7 @@ def f(x):
v = axes.get(self._AXIS_NAMES[axis])
if v is None:
continue
f = _get_rename_function(v)
f = self._get_rename_function(v)

baxis = self._get_block_manager_axis(axis)
if level is not None:
Expand Down Expand Up @@ -964,13 +964,18 @@ def rename_axis(self, mapper, axis=0, copy=True, inplace=False):
if non_mapper:
return self._set_axis_name(mapper, axis=axis, inplace=inplace)
else:
msg = ("Using 'rename_axis' to alter labels is deprecated. "
"Use '.rename' instead")
warnings.warn(msg, FutureWarning, stacklevel=2)
axis = self._get_axis_name(axis)
d = {'copy': copy, 'inplace': inplace}
d[axis] = mapper
return self.rename(**d)
# msg = ("Using 'rename_axis' to alter labels is deprecated. "
# "Use '.rename' instead")
# warnings.warn(msg, FutureWarning, stacklevel=2)
# axis = self._get_axis_name(axis)
# d = {'copy': copy, 'inplace': inplace}
# d[axis] = mapper
# return self.rename(**d)
f = self._get_rename_function(mapper)
curnames = self._get_axis(axis).names
newnames = [f(name) for name in curnames]
return self._set_axis_name(newnames, axis=axis, inplace=inplace)


def _set_axis_name(self, name, axis=0, inplace=False):
"""
Expand Down
59 changes: 40 additions & 19 deletions pandas/tests/frame/test_alter_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,25 +451,46 @@ def test_rename_axis_inplace(self):
assert no_return is None
assert_frame_equal(result, expected)

def test_rename_axis_warns(self):
# https://github.com/pandas-dev/pandas/issues/17833
df = pd.DataFrame({"A": [1, 2], "B": [1, 2]})
with tm.assert_produces_warning(FutureWarning) as w:
df.rename_axis(id, axis=0)
assert 'rename' in str(w[0].message)

with tm.assert_produces_warning(FutureWarning) as w:
df.rename_axis({0: 10, 1: 20}, axis=0)
assert 'rename' in str(w[0].message)

with tm.assert_produces_warning(FutureWarning) as w:
df.rename_axis(id, axis=1)
assert 'rename' in str(w[0].message)

with tm.assert_produces_warning(FutureWarning) as w:
df['A'].rename_axis(id)
assert 'rename' in str(w[0].message)

# def test_rename_axis_warns(self):
# # https://github.com/pandas-dev/pandas/issues/17833
# df = pd.DataFrame({"A": [1, 2], "B": [1, 2]})
# with tm.assert_produces_warning(FutureWarning) as w:
# df.rename_axis(id, axis=0)
# assert 'rename' in str(w[0].message)
#
# with tm.assert_produces_warning(FutureWarning) as w:
# df.rename_axis({0: 10, 1: 20}, axis=0)
# assert 'rename' in str(w[0].message)
#
# with tm.assert_produces_warning(FutureWarning) as w:
# df.rename_axis(id, axis=1)
# assert 'rename' in str(w[0].message)
#
# with tm.assert_produces_warning(FutureWarning) as w:
# df['A'].rename_axis(id)
# assert 'rename' in str(w[0].message)

def test_rename_axis_mapper(self):
mi = pd.MultiIndex.from_product([['a', 'b', 'c'], [1, 2]],
names=['ll', 'nn'])

df = pd.DataFrame({'x': [i for i in range(len(mi))],
'y' : [i*10 for i in range(len(mi))]},
index=mi)
result = df.rename_axis('cols', axis=1)
tm.assert_index_equal(result.columns,
pd.Index(['x', 'y'], name='cols'))

result = result.rename_axis({'cols' : 'new'}, axis=1)
tm.assert_index_equal(result.columns,
pd.Index(['x', 'y'], name='new'))

result = df.rename_axis({'ll' : 'foo'})
assert result.index.names == ['foo', 'nn']

result = df.rename_axis(str.upper, axis=0)
assert result.index.names == ['LL', 'NN']

def test_rename_multiindex(self):

tuples_index = [('foo1', 'bar1'), ('foo2', 'bar2')]
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/io/test_pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1288,8 +1288,8 @@ def test_append_with_strings(self):
with ensure_clean_store(self.path) as store:
with catch_warnings(record=True):
wp = tm.makePanel()
wp2 = wp.rename_axis(
{x: "%s_extra" % x for x in wp.minor_axis}, axis=2)
wp2 = wp.rename(
minor_axis = {x: "%s_extra" % x for x in wp.minor_axis})

def check_col(key, name, size):
assert getattr(store.get_storer(key)
Expand Down
9 changes: 4 additions & 5 deletions pandas/tests/reshape/test_concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -1401,12 +1401,11 @@ def df():
panel1 = make_panel()
panel2 = make_panel()

panel2 = panel2.rename_axis(dict((x, "%s_1" % x)
for x in panel2.major_axis),
axis=1)
panel2 = panel2.rename(major_axis=dict((x, "%s_1" % x)
for x in panel2.major_axis))

panel3 = panel2.rename_axis(lambda x: '%s_1' % x, axis=1)
panel3 = panel3.rename_axis(lambda x: '%s_1' % x, axis=2)
panel3 = panel2.rename(major_axis=lambda x: '%s_1' % x)
panel3 = panel3.rename(minor_axis=lambda x: '%s_1' % x)

# it works!
concat([panel1, panel3], axis=1, verify_integrity=True)
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/test_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -2176,16 +2176,16 @@ def test_rename(self):
with catch_warnings(record=True):
mapper = {'ItemA': 'foo', 'ItemB': 'bar', 'ItemC': 'baz'}

renamed = self.panel.rename_axis(mapper, axis=0)
renamed = self.panel.rename(items=mapper)
exp = Index(['foo', 'bar', 'baz'])
tm.assert_index_equal(renamed.items, exp)

renamed = self.panel.rename_axis(str.lower, axis=2)
renamed = self.panel.rename(minor_axis=str.lower)
exp = Index(['a', 'b', 'c', 'd'])
tm.assert_index_equal(renamed.minor_axis, exp)

# don't copy
renamed_nocopy = self.panel.rename_axis(mapper, axis=0, copy=False)
renamed_nocopy = self.panel.rename(items=mapper, copy=False)
renamed_nocopy['foo'] = 3.
assert (self.panel['ItemA'].values == 3).all()

Expand Down
0