Skip to content

API: allow list-like to DataFrame rename #15029

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
19 changes: 19 additions & 0 deletions doc/source/indexing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1586,6 +1586,25 @@ If you create an index yourself, you can just assign it to the ``index`` field:

data.index = index

.. versionadded:: 0.20.0

A new index can also be created on an existing object by passing values
to the ``rename`` method.

.. ipython:: python
:suppress:

data = data.reset_index()

.. ipython:: python

data
data.rename(index=['a', 'b', 'c', 'd'])
data.rename(columns=['q', 'w', 'r', 't'])




.. _indexing.view_versus_copy:

Returning a view versus a copy
Expand Down
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.20.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ Other enhancements
- ``pandas.io.json.json_normalize()`` gained the option ``errors='ignore'|'raise'``; the default is ``errors='raise'`` which is backward compatible. (:issue:`14583`)

- ``.select_dtypes()`` now allows the string 'datetimetz' to generically select datetimes with tz (:issue:`14910`)

- ``pd.DataFrame.rename`` now accepts a list-like for the ``index`` and ``columns`` parameters to assign new axis values (:issue:`14829`)

.. _whatsnew_0200.api_breaking:

Expand Down
5 changes: 5 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2842,6 +2842,11 @@ def set_index(self, keys, drop=True, append=False, inplace=False,
Returns
-------
dataframe : DataFrame

See Also
--------
DataFrame.rename

"""
if not isinstance(keys, list):
keys = [keys]
Expand Down
19 changes: 14 additions & 5 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,7 @@ def swaplevel(self, i=-2, j=-1, axis=0):
----------
%(axes)s : scalar, list-like, dict-like or function, optional
Scalar or list-like will alter the ``Series.name`` attribute,
and raise on DataFrame or Panel.
for DataFrame list-like will form new values for the axes,
dict-like or functions are transformations to apply to
that axis' values
copy : boolean, default True
Expand Down Expand Up @@ -635,6 +635,11 @@ def swaplevel(self, i=-2, j=-1, axis=0):
0 1 4
1 2 5
2 3 6
>>> df.rename(index=['a', 'b', 'c'], columns=[1, 2])
1 2
a 1 4
b 2 5
c 3 6
"""

@Appender(_shared_docs['rename'] % dict(axes='axes keywords for this'
Expand Down Expand Up @@ -672,13 +677,17 @@ def f(x):
# start in the axis order to eliminate too many copies
for axis in lrange(self._AXIS_LEN):
v = axes.get(self._AXIS_NAMES[axis])
baxis = self._get_block_manager_axis(axis)
if v is None:
continue
f = _get_rename_function(v)

baxis = self._get_block_manager_axis(axis)
result._data = result._data.rename_axis(f, axis=baxis, copy=copy)
result._clear_item_cache()
f = _get_rename_function(v)
if is_list_like(f) and not callable(f):
result._set_axis(axis=baxis, labels=v)
else:
result._data = result._data.rename_axis(f, axis=baxis,
copy=copy)
result._clear_item_cache()

if inplace:
self._update_inplace(result._data)
Expand Down
24 changes: 24 additions & 0 deletions pandas/tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1504,6 +1504,30 @@ def test_to_xarray(self):
expected,
check_index_type=False)

def test_rename_list_like(self):
# GH 14829
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}, columns=['a', 'b'])

expected = df.copy()
expected.columns = ['J', 'K']
result = df.rename(columns=['J', 'K'])
assert_frame_equal(result, expected)

expected.index = ['a', 'b']
for box in [list, np.array, Index]:
result = df.rename(columns=box(['J', 'K']), index=box(['a', 'b']))
assert_frame_equal(result, expected)

result = df.copy()
result.rename(columns=['J', 'K'], index=['a', 'b'], inplace=True)
Copy link
Contributor

Choose a reason for hiding this comment

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

test with ndarray and with an Index
a scalar should error yes?

assert_frame_equal(result, expected)

with tm.assertRaises(ValueError):
df.rename(index=[1, 3, 3])

with tm.assertRaises(TypeError):
df.rename(index=1)


class TestPanel(tm.TestCase, Generic):
_typ = Panel
Expand Down