Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 24 additions & 55 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3913,62 +3913,31 @@ def drop(self, labels=None, axis=0, index=None, columns=None,
('inplace', False),
('level', None),
('errors', 'ignore')])
@Substitution(klass="DataFrame",
altered="axis labels",
alternative_use="",
specific_parameters="mapper : dict-like or function\n\t\t"
"Dict-like or functions transformation "
"to apply to that axis' values. Use"
" ``axis`` to specify the axis to target"
" with ``mapper``.\n\t"
"index : dict-like or function\n\t\t"
"Alternative to specifying axis ("
"``mapper, axis=0`` is equivalent to "
"``index=mapper``).\n\t"
"columns : dict-like or function\n\t\t"
"Alternative to specifying axis ("
"``mapper, axis=1`` is equivalent to "
"``columns=mapper``).\n\t"
"axis : int or str\n\t\t"
"Axis to target with mapper. Can be "
"either the axis name ('index', "
"'columns') or number (0, 1). The "
"default is 'index'.".expandtabs()
)
@Substitution(generic_documentation=NDFrame.rename.__doc__)
def rename(self, *args, **kwargs):
"""
Alter axes labels.

Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.

See the :ref:`user guide <basics.rename>` for more.

Parameters
----------
mapper : dict-like or function
Dict-like or functions transformations to apply to
that axis' values. Use either ``mapper`` and ``axis`` to
specify the axis to target with ``mapper``, or ``index`` and
``columns``.
index : dict-like or function
Alternative to specifying axis (``mapper, axis=0``
is equivalent to ``index=mapper``).
columns : dict-like or function
Alternative to specifying axis (``mapper, axis=1``
is equivalent to ``columns=mapper``).
axis : int or str
Axis to target with ``mapper``. Can be either the axis name
('index', 'columns') or number (0, 1). The default is 'index'.
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Whether to return a new DataFrame. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.
errors : {'ignore', 'raise'}, default 'ignore'
If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
or `columns` contains labels that are not present in the Index
being transformed.
If 'ignore', existing keys will be renamed and extra keys will be
ignored.

Returns
-------
DataFrame
DataFrame with the renamed axis labels.

Raises
------
KeyError
If any of the labels is not found in the selected axis and
"errors='raise'".

See Also
--------
DataFrame.rename_axis : Set the name of the axis.

"""%(generic_documentation)s
Examples
--------

Expand Down
98 changes: 14 additions & 84 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -958,23 +958,21 @@ def swaplevel(self, i=-2, j=-1, axis=0):

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

def rename(self, *args, **kwargs):
"""
Alter axes input function or functions. Function / dict values must be
unique (1-to-1). Labels not contained in a dict / Series will be left
as-is. Extra labels listed don't throw an error. Alternatively, change
``Series.name`` with a scalar value (Series only).
Alter %(altered)s.

Function / dict values must be unique (1-to-1). Labels not contained in
the %(altered)s will be left as-is. Extra labels listed do not throw an
error, unless "errors='raise'". %(alternative_use)s

See the :ref:`user guide <basics.rename>` for more.

Parameters
----------
%(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.
dict-like or functions are transformations to apply to
that axis' values
%(specific_parameters)s
copy : bool, default True
Also copy underlying data.
Whether to copy underlying data.
inplace : bool, default False
Whether to return a new %(klass)s. If True then value of copy is
ignored.
Expand All @@ -990,88 +988,20 @@ def rename(self, *args, **kwargs):

Returns
-------
renamed : %(klass)s (new object)
%(klass)s
%(klass)s with %(altered)s altered.

Raises
------
KeyError
If any of the labels is not found in the selected axis and
"errors='raise'".
``errors='raise'``.

See Also
--------
NDFrame.rename_axis

Examples
--------

>>> s = pd.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Name: my_name, dtype: int64
>>> s.rename(lambda x: x ** 2) # function, changes labels
0 1
1 2
4 3
dtype: int64
>>> s.rename({1: 3, 2: 5}) # mapping, changes labels
0 1
3 2
5 3
dtype: int64

Since ``DataFrame`` doesn't have a ``.name`` attribute,
only mapping-type arguments are allowed.

>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(2)
Traceback (most recent call last):
...
TypeError: 'int' object is not callable

``DataFrame.rename`` supports two calling conventions

* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``

We *highly* recommend using keyword arguments to clarify your
intent.

>>> df.rename(index=str, columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6

>>> df.rename(index=str, columns={"A": "a", "C": "c"})
a B
0 1 4
1 2 5
2 3 6

Using axis-style parameters

>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6

>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6

See the :ref:`user guide <basics.rename>` for more.
%(klass)s.rename_axis: Set the name of the axis.
"""

axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
copy = kwargs.pop('copy', True)
inplace = kwargs.pop('inplace', False)
Expand Down
86 changes: 84 additions & 2 deletions pandas/core/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -1249,9 +1249,91 @@ def reindex(self, *args, **kwargs):
result = super(Panel, self).reindex(**kwargs)
return result

@Substitution(**_shared_doc_kwargs)
@Appender(NDFrame.rename.__doc__)
@Substitution(klass="Panel",
altered="axes input function or functions",
alternative_use="",
specific_parameters="items, major_axis, minor_axis : "
"scalar, list-like, dict-like or "
"function, optional\n\t\t"
"Scalar or list-like will alter the "
"Series.name attribute, and raise on "
"DataFrame or Panel, dict-like or "
"functions are transformations to "
"apply to that axis'"
" values.".expandtabs())
@Substitution(generic_documentation=NDFrame.rename.__doc__)
def rename(self, items=None, major_axis=None, minor_axis=None, **kwargs):
"""%(generic_documentation)s
Examples
--------

>>> s = pd.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Name: my_name, dtype: int64
>>> s.rename(lambda x: x ** 2) # function, changes labels
0 1
1 2
4 3
dtype: int64
>>> s.rename({1: 3, 2: 5}) # mapping, changes labels
0 1
3 2
5 3
dtype: int64

Since ``DataFrame`` doesn't have a ``.name`` attribute,
only mapping-type arguments are allowed.

>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(2)
Traceback (most recent call last):
...
TypeError: 'int' object is not callable

``DataFrame.rename`` supports two calling conventions

* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``

We *highly* recommend using keyword arguments to clarify your
intent.

>>> df.rename(index=str, columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6

>>> df.rename(index=str, columns={"A": "a", "C": "c"})
a B
0 1 4
1 2 5
2 3 6

Using axis-style parameters

>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6

>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6

See the :ref:`user guide <basics.rename>` for more.
"""
major_axis = (major_axis if major_axis is not None else
kwargs.pop('major', None))
minor_axis = (minor_axis if minor_axis is not None else
Expand Down
51 changes: 14 additions & 37 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -3733,43 +3733,20 @@ def align(self, other, join='outer', axis=None, level=None, copy=True,
limit=limit, fill_axis=fill_axis,
broadcast_axis=broadcast_axis)

@Substitution(klass="Series",
altered="Series index labels or name",
alternative_use="Alternatively, change Series.name with a "
"scalar value.",
specific_parameters="index : scalar, hashable sequence"
" dict-like or function, optional\n\t\t"
"Dict-like or functions are "
"transformations to apply to the index. "
"Scalar or hashable sequence-like will "
"alter the Series.name "
"attribute.".expandtabs())
@Substitution(generic_documentation=generic.NDFrame.rename.__doc__)
def rename(self, index=None, **kwargs):
"""
Alter Series index labels or name.

Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.

Alternatively, change ``Series.name`` with a scalar value.

See the :ref:`user guide <basics.rename>` for more.

Parameters
----------
index : scalar, hashable sequence, dict-like or function, optional
dict-like or functions are transformations to apply to
the index.
Scalar or hashable sequence-like will alter the ``Series.name``
attribute.
copy : bool, default True
Whether to copy underlying data.
inplace : bool, default False
Whether to return a new Series. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.

Returns
-------
Series
Series with index labels or name altered.

See Also
--------
Series.rename_axis : Set the name of the axis.

"""%(generic_documentation)s
Examples
--------
>>> s = pd.Series([1, 2, 3])
Expand All @@ -3778,7 +3755,7 @@ def rename(self, index=None, **kwargs):
1 2
2 3
dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Expand Down