Skip to content

CLN: a batch of replacements of @Appender() with @doc() #33021

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

2 changes: 1 addition & 1 deletion pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,7 @@ def shift(self, periods=1, fill_value=None, axis=0):
"will raise in a future version, pass "
f"{self._scalar_type.__name__} instead.",
FutureWarning,
stacklevel=7,
stacklevel=9,
)
fill_value = new_fill

Expand Down
6 changes: 3 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3630,7 +3630,7 @@ def _reindex_multi(self, axes, copy, fill_value) -> "DataFrame":
fill_value=fill_value,
)

@Appender(_shared_docs["align"] % _shared_doc_kwargs)
@doc(NDFrame.align, **_shared_doc_kwargs)
def align(
self,
other,
Expand Down Expand Up @@ -4011,7 +4011,7 @@ def fillna(
downcast=downcast,
)

@Appender(_shared_docs["replace"] % _shared_doc_kwargs)
@doc(NDFrame.replace, **_shared_doc_kwargs)
def replace(
self,
to_replace=None,
Expand Down Expand Up @@ -4065,7 +4065,7 @@ def _replace_columnwise(
return
return res.__finalize__(self)

@Appender(_shared_docs["shift"] % _shared_doc_kwargs)
@doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"])
def shift(self, periods=1, freq=None, axis=0, fill_value=None) -> "DataFrame":
return super().shift(
periods=periods, freq=freq, axis=axis, fill_value=fill_value
Expand Down
138 changes: 65 additions & 73 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6162,12 +6162,20 @@ def bfill(
method="bfill", axis=axis, inplace=inplace, limit=limit, downcast=downcast
)

_shared_docs[
"replace"
] = """
@doc(klass=_shared_doc_kwargs["klass"])
def replace(
self,
to_replace=None,
value=None,
inplace=False,
limit=None,
regex=False,
method="pad",
):
"""
Replace values given in `to_replace` with `value`.

Values of the %(klass)s are replaced with other values dynamically.
Values of the {klass} are replaced with other values dynamically.
This differs from updating with ``.loc`` or ``.iloc``, which require
you to specify a location to update with some value.

Expand Down Expand Up @@ -6199,19 +6207,19 @@ def bfill(

- Dicts can be used to specify different replacement values
for different existing values. For example,
``{'a': 'b', 'y': 'z'}`` replaces the value 'a' with 'b' and
``{{'a': 'b', 'y': 'z'}}`` replaces the value 'a' with 'b' and
'y' with 'z'. To use a dict in this way the `value`
parameter should be `None`.
- For a DataFrame a dict can specify that different values
should be replaced in different columns. For example,
``{'a': 1, 'b': 'z'}`` looks for the value 1 in column 'a'
``{{'a': 1, 'b': 'z'}}`` looks for the value 1 in column 'a'
and the value 'z' in column 'b' and replaces these values
with whatever is specified in `value`. The `value` parameter
should not be ``None`` in this case. You can treat this as a
special case of passing two lists except that you are
specifying the column to search in.
- For a DataFrame nested dictionaries, e.g.,
``{'a': {'b': np.nan}}``, are read as follows: look in column
``{{'a': {{'b': np.nan}}}}``, are read as follows: look in column
'a' for the value 'b' and replace it with NaN. The `value`
parameter should be ``None`` to use a nested dict in this
way. You can nest regular expressions as well. Note that
Expand Down Expand Up @@ -6244,7 +6252,7 @@ def bfill(
string. Alternatively, this could be a regular expression or a
list, dict, or array of regular expressions in which case
`to_replace` must be ``None``.
method : {'pad', 'ffill', 'bfill', `None`}
method : {{'pad', 'ffill', 'bfill', `None`}}
The method to use when for replacement, when `to_replace` is a
scalar, list or tuple and `value` is ``None``.

Expand All @@ -6253,7 +6261,7 @@ def bfill(

Returns
-------
%(klass)s
{klass}
Object after replacement.

Raises
Expand All @@ -6279,8 +6287,8 @@ def bfill(

See Also
--------
%(klass)s.fillna : Fill NA values.
%(klass)s.where : Replace values based on boolean condition.
{klass}.fillna : Fill NA values.
{klass}.where : Replace values based on boolean condition.
Series.str.replace : Simple string replacement.

Notes
Expand Down Expand Up @@ -6312,9 +6320,9 @@ def bfill(
4 4
dtype: int64

>>> df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
>>> df = pd.DataFrame({{'A': [0, 1, 2, 3, 4],
... 'B': [5, 6, 7, 8, 9],
... 'C': ['a', 'b', 'c', 'd', 'e']})
... 'C': ['a', 'b', 'c', 'd', 'e']}})
>>> df.replace(0, 5)
A B C
0 5 5 a
Expand Down Expand Up @@ -6351,23 +6359,23 @@ def bfill(

**dict-like `to_replace`**

>>> df.replace({0: 10, 1: 100})
>>> df.replace({{0: 10, 1: 100}})
A B C
0 10 5 a
1 100 6 b
2 2 7 c
3 3 8 d
4 4 9 e

>>> df.replace({'A': 0, 'B': 5}, 100)
>>> df.replace({{'A': 0, 'B': 5}}, 100)
A B C
0 100 100 a
1 1 6 b
2 2 7 c
3 3 8 d
4 4 9 e

>>> df.replace({'A': {0: 100, 4: 400}})
>>> df.replace({{'A': {{0: 100, 4: 400}}}})
A B C
0 100 5 a
1 1 6 b
Expand All @@ -6377,15 +6385,15 @@ def bfill(

**Regular expression `to_replace`**

>>> df = pd.DataFrame({'A': ['bat', 'foo', 'bait'],
... 'B': ['abc', 'bar', 'xyz']})
>>> df = pd.DataFrame({{'A': ['bat', 'foo', 'bait'],
... 'B': ['abc', 'bar', 'xyz']}})
>>> df.replace(to_replace=r'^ba.$', value='new', regex=True)
A B
0 new abc
1 foo new
2 bait xyz

>>> df.replace({'A': r'^ba.$'}, {'A': 'new'}, regex=True)
>>> df.replace({{'A': r'^ba.$'}}, {{'A': 'new'}}, regex=True)
A B
0 new abc
1 foo bar
Expand All @@ -6397,7 +6405,7 @@ def bfill(
1 foo new
2 bait xyz

>>> df.replace(regex={r'^ba.$': 'new', 'foo': 'xyz'})
>>> df.replace(regex={{r'^ba.$': 'new', 'foo': 'xyz'}})
A B
0 new abc
1 xyz new
Expand All @@ -6413,28 +6421,28 @@ def bfill(
the data types in the `to_replace` parameter must match the data
type of the value being replaced:

>>> df = pd.DataFrame({'A': [True, False, True],
... 'B': [False, True, False]})
>>> df.replace({'a string': 'new value', True: False}) # raises
>>> df = pd.DataFrame({{'A': [True, False, True],
... 'B': [False, True, False]}})
>>> df.replace({{'a string': 'new value', True: False}}) # raises
Traceback (most recent call last):
...
TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'

This raises a ``TypeError`` because one of the ``dict`` keys is not of
the correct type for replacement.

Compare the behavior of ``s.replace({'a': None})`` and
Compare the behavior of ``s.replace({{'a': None}})`` and
``s.replace('a', None)`` to understand the peculiarities
of the `to_replace` parameter:

>>> s = pd.Series([10, 'a', 'a', 'b', 'a'])

When one uses a dict as the `to_replace` value, it is like the
value(s) in the dict are equal to the `value` parameter.
``s.replace({'a': None})`` is equivalent to
``s.replace(to_replace={'a': None}, value=None, method=None)``:
``s.replace({{'a': None}})`` is equivalent to
``s.replace(to_replace={{'a': None}}, value=None, method=None)``:

>>> s.replace({'a': None})
>>> s.replace({{'a': None}})
0 10
1 None
2 None
Expand All @@ -6457,17 +6465,6 @@ def bfill(
4 b
dtype: object
"""

@Appender(_shared_docs["replace"] % _shared_doc_kwargs)
def replace(
self,
to_replace=None,
value=None,
inplace=False,
limit=None,
regex=False,
method="pad",
):
if not (
is_scalar(to_replace)
or is_re_compilable(to_replace)
Expand Down Expand Up @@ -8246,17 +8243,29 @@ def ranker(data):

return ranker(data)

_shared_docs[
"align"
] = """
@doc(**_shared_doc_kwargs)
def align(
self,
other,
join="outer",
axis=None,
level=None,
copy=True,
fill_value=None,
method=None,
limit=None,
fill_axis=0,
broadcast_axis=None,
):
"""
Align two objects on their axes with the specified join method.

Join method is specified for each axis Index.

Parameters
----------
other : DataFrame or Series
join : {'outer', 'inner', 'left', 'right'}, default 'outer'
join : {{'outer', 'inner', 'left', 'right'}}, default 'outer'
axis : allowed axis of the other object, default None
Align on index (0), columns (1), or both (None).
level : int or level name, default None
Expand All @@ -8268,7 +8277,7 @@ def ranker(data):
fill_value : scalar, default np.NaN
Value to use for missing values. Defaults to NaN, but can be any
"compatible" value.
method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
method : {{'backfill', 'bfill', 'pad', 'ffill', None}}, default None
Method to use for filling holes in reindexed Series:

- pad / ffill: propagate last valid observation forward to next valid.
Expand All @@ -8281,32 +8290,18 @@ def ranker(data):
be partially filled. If method is not specified, this is the
maximum number of entries along the entire axis where NaNs will be
filled. Must be greater than 0 if not None.
fill_axis : %(axes_single_arg)s, default 0
fill_axis : {axes_single_arg}, default 0
Filling axis, method and limit.
broadcast_axis : %(axes_single_arg)s, default None
broadcast_axis : {axes_single_arg}, default None
Broadcast values along this axis, if aligning two objects of
different dimensions.

Returns
-------
(left, right) : (%(klass)s, type of other)
(left, right) : ({klass}, type of other)
Aligned objects.
"""

@Appender(_shared_docs["align"] % _shared_doc_kwargs)
def align(
self,
other,
join="outer",
axis=None,
level=None,
copy=True,
fill_value=None,
method=None,
limit=None,
fill_axis=0,
broadcast_axis=None,
):
method = missing.clean_fill_method(method)

if broadcast_axis == 1 and self.ndim != other.ndim:
Expand Down Expand Up @@ -8850,9 +8845,11 @@ def mask(
errors=errors,
)

_shared_docs[
"shift"
] = """
@doc(klass=_shared_doc_kwargs["klass"])
def shift(
self: FrameOrSeries, periods=1, freq=None, axis=0, fill_value=None
) -> FrameOrSeries:
"""
Shift index by desired number of periods with an optional time `freq`.

When `freq` is not passed, shift the index without realigning the data.
Expand All @@ -8869,7 +8866,7 @@ def mask(
If `freq` is specified then the index values are shifted but the
data is not realigned. That is, use `freq` if you would like to
extend the index when shifting and preserve the original data.
axis : {0 or 'index', 1 or 'columns', None}, default None
axis : {{0 or 'index', 1 or 'columns', None}}, default None
Shift direction.
fill_value : object, optional
The scalar value to use for newly introduced missing values.
Expand All @@ -8882,7 +8879,7 @@ def mask(

Returns
-------
%(klass)s
{klass}
Copy of input object, shifted.

See Also
Expand All @@ -8895,9 +8892,9 @@ def mask(

Examples
--------
>>> df = pd.DataFrame({'Col1': [10, 20, 15, 30, 45],
>>> df = pd.DataFrame({{'Col1': [10, 20, 15, 30, 45],
... 'Col2': [13, 23, 18, 33, 48],
... 'Col3': [17, 27, 22, 37, 52]})
... 'Col3': [17, 27, 22, 37, 52]}})

>>> df.shift(periods=3)
Col1 Col2 Col3
Expand All @@ -8922,12 +8919,7 @@ def mask(
2 0 0 0
3 10 13 17
4 20 23 27
"""

@Appender(_shared_docs["shift"] % _shared_doc_kwargs)
def shift(
self: FrameOrSeries, periods=1, freq=None, axis=0, fill_value=None
) -> FrameOrSeries:
"""
if periods == 0:
return self.copy()

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import pandas.core.algorithms as algos
from pandas.core.base import DataError, ShallowMixin
from pandas.core.generic import _shared_docs
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.groupby.base import GroupByMixin
from pandas.core.groupby.generic import SeriesGroupBy
from pandas.core.groupby.groupby import GroupBy, _GroupBy, _pipe_template, get_groupby
Expand Down Expand Up @@ -773,7 +773,7 @@ def fillna(self, method, limit=None):
"""
return self._upsample(method, limit=limit)

@Appender(_shared_docs["interpolate"] % _shared_docs_kwargs)
@doc(NDFrame.interpolate, **_shared_docs_kwargs)
def interpolate(
self,
method="linear",
Expand Down
Loading