Skip to content

ENH: Add replace method to Index #32542

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 54 commits into from
Closed
Show file tree
Hide file tree
Changes from 46 commits
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
22d53cc
initial coommit & test
oguzhanogreden Mar 2, 2020
47a14fa
Initial commit & test
oguzhanogreden Mar 2, 2020
fbbc745
Third case, not implementing
oguzhanogreden Mar 2, 2020
5cd5d65
replace values list with scalar
oguzhanogreden Mar 4, 2020
734c750
backfill case
oguzhanogreden Mar 4, 2020
becbc09
Add replace_single and regex cases
oguzhanogreden Mar 7, 2020
ae20f64
Not implementing inplace in light of #16529.
oguzhanogreden Mar 8, 2020
4fa5f11
Clean unnecessary errors
oguzhanogreden Mar 8, 2020
4d3ec7e
remove unused inplace parameters/arguments
oguzhanogreden Mar 8, 2020
1737372
remove filter from _replace_single() method()
oguzhanogreden Mar 8, 2020
554ce48
Remove unnecessary comment
oguzhanogreden Mar 8, 2020
09f3a15
Add documentation to replace_list
oguzhanogreden Mar 8, 2020
f81efc1
Fix import
oguzhanogreden Mar 8, 2020
e1711d8
Address minor comments - i
oguzhanogreden Mar 8, 2020
1ebc201
Revert moving imports to import section
oguzhanogreden Mar 8, 2020
f93adb8
Minor comments and parametrized tests
oguzhanogreden Mar 8, 2020
0475c86
Raise NotImplemented for Categorical- and MultiIndex
oguzhanogreden Mar 11, 2020
70896a7
commit test code
oguzhanogreden Jun 19, 2020
46c4712
reuse code & add tests
oguzhanogreden Jun 19, 2020
786208b
Again, add type ignore
oguzhanogreden Jun 20, 2020
6dc5f8b
Move type ignore to correct line...
oguzhanogreden Jun 20, 2020
1512edf
add docstrings
oguzhanogreden Jul 18, 2020
241721a
Merge remote-tracking branch 'upstream/master' into index-replace-bck
oguzhanogreden Jul 18, 2020
be1d0ac
I had removed defaults by mistake, added them again
oguzhanogreden Jul 19, 2020
aeb2759
Add defaults to multiindex as well
oguzhanogreden Jul 19, 2020
db58359
Update whatsnew
oguzhanogreden Jul 20, 2020
a6e01eb
Merge remote-tracking branch 'upstream/master' into index-replace-bck
oguzhanogreden Jul 21, 2020
0970112
Move shared docs to common.shared_docs
oguzhanogreden Jul 27, 2020
1e2efc3
Merge remote-tracking branch 'upstream/master' into index-replace-bck
oguzhanogreden Jul 27, 2020
7bdc7a8
Cache errors not caught by checks
oguzhanogreden Jul 27, 2020
46d5c5a
Merge remote-tracking branch 'upstream/master' into index-replace-bck
oguzhanogreden Aug 1, 2020
cac074f
Merge remote-tracking branch 'upstream/master' into index-replace-bck
oguzhanogreden Aug 6, 2020
ff27ce4
Merge branch 'master' into index-replace-bck
oguzhanogreden Nov 11, 2020
e315717
'public' shared_doc_kwargs
oguzhanogreden Nov 11, 2020
7406775
revert 'public' shared_doc_kwargs adjust validation
oguzhanogreden Nov 11, 2020
7b4a2b0
Move whatsnes
oguzhanogreden Nov 11, 2020
5f86494
Add replace method for categorical index
oguzhanogreden Nov 11, 2020
61b8ac5
Revert changes and a better NotImplementedError message
oguzhanogreden Nov 16, 2020
1bb05f9
Grammar fix in whatsnew
oguzhanogreden Nov 16, 2020
c955338
fix formatting
oguzhanogreden Nov 16, 2020
01ac22f
Revert unintended formatting changes in core/shared_docs.py
oguzhanogreden Nov 22, 2020
e6a4e8d
test case for change identified by the doctest & formatting by black
oguzhanogreden Nov 22, 2020
7d7e5ca
Remove stale documentation.
oguzhanogreden Nov 22, 2020
35d493a
Merge remote-tracking branch 'upstream/master' into index-replace-bck
oguzhanogreden Nov 22, 2020
b73c774
Merge branch 'master' into index-replace
oguzhanogreden Nov 27, 2020
0801abf
Merge branch 'master' of github.com:pandas-dev/pandas into index-repl…
oguzhanogreden Nov 30, 2020
800aef7
Merge branch 'master' into index-replace
oguzhanogreden Dec 13, 2020
eb784b5
Address comments and add tests
oguzhanogreden Dec 13, 2020
a23faaf
Merge branch 'index-replace' of https://github.com/oguzhanogreden/pan…
oguzhanogreden Dec 13, 2020
2a778bb
C408
oguzhanogreden Dec 13, 2020
d4ade69
Merge branch 'master' of github.com:pandas-dev/pandas into index-repl…
oguzhanogreden Jan 15, 2021
7fddde6
revert validate_unwanted_patterns
oguzhanogreden Jan 15, 2021
f4fa3d6
Move what's new and tidy up @docs
oguzhanogreden Jan 15, 2021
62bd25e
Merge branch 'master' into index-replace
oguzhanogreden Jan 18, 2021
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ Other enhancements
- Improve numerical stability for :meth:`.Rolling.skew`, :meth:`.Rolling.kurt`, :meth:`Expanding.skew` and :meth:`Expanding.kurt` through implementation of Kahan summation (:issue:`6929`)
- Improved error reporting for subsetting columns of a :class:`.DataFrameGroupBy` with ``axis=1`` (:issue:`37725`)
- Implement method ``cross`` for :meth:`DataFrame.merge` and :meth:`DataFrame.join` (:issue:`5401`)
- :class:`Index` and :class:`MultiIndex` now have a ``replace()`` method (:issue:`19495`).

.. ---------------------------------------------------------------------------

Expand Down
8 changes: 7 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@
)
from pandas.core.reshape.melt import melt
from pandas.core.series import Series
from pandas.core.shared_docs import _shared_doc_kwargs as core_shared_doc_kwargs
from pandas.core.sorting import get_group_index, lexsort_indexer, nargsort

from pandas.io.common import get_handle
Expand Down Expand Up @@ -4520,7 +4521,12 @@ def pop(self, item: Label) -> Series:
"""
return super().pop(item=item)

@doc(NDFrame.replace, **_shared_doc_kwargs)
@doc(
NDFrame.replace,
inplace=core_shared_doc_kwargs["inplace"],
replace_iloc=core_shared_doc_kwargs["replace_iloc"],
**_shared_doc_kwargs,
)
def replace(
self,
to_replace=None,
Expand Down
305 changes: 18 additions & 287 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@
from pandas.core.internals import BlockManager
from pandas.core.missing import find_valid_index
from pandas.core.ops import align_method_FRAME
from pandas.core.shared_docs import _shared_docs
from pandas.core.shared_docs import _shared_doc_kwargs, _shared_docs
from pandas.core.sorting import get_indexer_indexer
from pandas.core.window import Expanding, ExponentialMovingWindow, Rolling, Window

Expand All @@ -128,15 +128,17 @@
# goal is to be able to define the docs close to function, while still being
# able to share
_shared_docs = {**_shared_docs}
_shared_doc_kwargs = {
"axes": "keywords for axes",
"klass": "Series/DataFrame",
"axes_single_arg": "int or labels for object",
"args_transpose": "axes to permute (int or label for object)",
"optional_by": """
by : str or list of str
Name or list of names to sort by""",
}
_shared_doc_kwargs.update(
dict(
axes="keywords for axes",
klass="Series/DataFrame",
axes_single_arg="int or labels for object",
args_transpose="axes to permute (int or label for object)",
optional_by="""
by : str or list of str
Name or list of names to sort by""",
)
)


bool_t = bool # Need alias because NDFrame has def bool:
Expand Down Expand Up @@ -6465,7 +6467,12 @@ def bfill(

backfill = bfill

@doc(klass=_shared_doc_kwargs["klass"])
@doc(
_shared_docs["to_replace"],
klass=_shared_doc_kwargs["klass"],
inplace=_shared_doc_kwargs["inplace"],
replace_iloc=_shared_doc_kwargs["replace_iloc"],
)
def replace(
self,
to_replace=None,
Expand All @@ -6475,282 +6482,6 @@ def replace(
regex=False,
method="pad",
):
"""
Replace values given in `to_replace` with `value`.

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.

Parameters
----------
to_replace : str, regex, list, dict, Series, int, float, or None
How to find the values that will be replaced.

* numeric, str or regex:

- numeric: numeric values equal to `to_replace` will be
replaced with `value`
- str: string exactly matching `to_replace` will be replaced
with `value`
- regex: regexs matching `to_replace` will be replaced with
`value`

* list of str, regex, or numeric:

- First, if `to_replace` and `value` are both lists, they
**must** be the same length.
- Second, if ``regex=True`` then all of the strings in **both**
lists will be interpreted as regexs otherwise they will match
directly. This doesn't matter much for `value` since there
are only a few possible substitution regexes you can use.
- str, regex and numeric rules apply as above.

* dict:

- 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
'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'
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' 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
column names (the top-level dictionary keys in a nested
dictionary) **cannot** be regular expressions.

* None:

- This means that the `regex` argument must be a string,
compiled regular expression, or list, dict, ndarray or
Series of such elements. If `value` is also ``None`` then
this **must** be a nested dictionary or Series.

See the examples section for examples of each of these.
value : scalar, dict, list, str, regex, default None
Value to replace any values matching `to_replace` with.
For a DataFrame a dict of values can be used to specify which
value to use for each column (columns not in the dict will not be
filled). Regular expressions, strings and lists or dicts of such
objects are also allowed.
inplace : bool, default False
If True, in place. Note: this will modify any
other views on this object (e.g. a column from a DataFrame).
Returns the caller if this is True.
limit : int or None, default None
Maximum size gap to forward or backward fill.
regex : bool or same types as `to_replace`, default False
Whether to interpret `to_replace` and/or `value` as regular
expressions. If this is ``True`` then `to_replace` *must* be a
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`}}
The method to use when for replacement, when `to_replace` is a
scalar, list or tuple and `value` is ``None``.

Returns
-------
{klass} or None
Object after replacement or None if ``inplace=True``.

Raises
------
AssertionError
* If `regex` is not a ``bool`` and `to_replace` is not
``None``.

TypeError
* If `to_replace` is not a scalar, array-like, ``dict``, or ``None``
* If `to_replace` is a ``dict`` and `value` is not a ``list``,
``dict``, ``ndarray``, or ``Series``
* If `to_replace` is ``None`` and `regex` is not compilable
into a regular expression or is a list, dict, ndarray, or
Series.
* When replacing multiple ``bool`` or ``datetime64`` objects and
the arguments to `to_replace` does not match the type of the
value being replaced

ValueError
* If a ``list`` or an ``ndarray`` is passed to `to_replace` and
`value` but they are not the same length.

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

Notes
-----
* Regex substitution is performed under the hood with ``re.sub``. The
rules for substitution for ``re.sub`` are the same.
* Regular expressions will only substitute on strings, meaning you
cannot provide, for example, a regular expression matching floating
point numbers and expect the columns in your frame that have a
numeric dtype to be matched. However, if those floating point
numbers *are* strings, then you can do this.
* This method has *a lot* of options. You are encouraged to experiment
and play with this method to gain intuition about how it works.
* When dict is used as the `to_replace` value, it is like
key(s) in the dict are the to_replace part and
value(s) in the dict are the value parameter.

Examples
--------

**Scalar `to_replace` and `value`**

>>> s = pd.Series([0, 1, 2, 3, 4])
>>> s.replace(0, 5)
0 5
1 1
2 2
3 3
4 4
dtype: int64

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

**List-like `to_replace`**

>>> df.replace([0, 1, 2, 3], 4)
A B C
0 4 5 a
1 4 6 b
2 4 7 c
3 4 8 d
4 4 9 e

>>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])
A B C
0 4 5 a
1 3 6 b
2 2 7 c
3 1 8 d
4 4 9 e

>>> s.replace([1, 2], method='bfill')
0 0
1 3
2 3
3 3
4 4
dtype: int64

**dict-like `to_replace`**

>>> 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)
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}}}})
A B C
0 100 5 a
1 1 6 b
2 2 7 c
3 3 8 d
4 400 9 e

**Regular expression `to_replace`**

>>> 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)
A B
0 new abc
1 foo bar
2 bait xyz

>>> df.replace(regex=r'^ba.$', value='new')
A B
0 new abc
1 foo new
2 bait xyz

>>> df.replace(regex={{r'^ba.$': 'new', 'foo': 'xyz'}})
A B
0 new abc
1 xyz new
2 bait xyz

>>> df.replace(regex=[r'^ba.$', 'foo'], value='new')
A B
0 new abc
1 new new
2 bait xyz

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}})
0 10
1 None
2 None
3 b
4 None
dtype: object

When ``value=None`` and `to_replace` is a scalar, list or
tuple, `replace` uses the method parameter (default 'pad') to do the
replacement. So this is why the 'a' values are being replaced by 10
in rows 1 and 2 and 'b' in row 4 in this case.
The command ``s.replace('a', None)`` is actually equivalent to
``s.replace(to_replace='a', value=None, method='pad')``:

>>> s.replace('a', None)
0 10
1 10
2 10
3 b
4 b
dtype: object
"""
if not (
is_scalar(to_replace)
or is_re_compilable(to_replace)
Expand Down
22 changes: 22 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
from pandas.core.indexes.frozen import FrozenList
from pandas.core.ops import get_op_result_name
from pandas.core.ops.invalid import make_invalid_op
from pandas.core.shared_docs import _shared_docs
from pandas.core.sorting import ensure_key_mapped, nargsort
from pandas.core.strings import StringMethods

Expand Down Expand Up @@ -1441,6 +1442,27 @@ def rename(self, name, inplace=False):
"""
return self.set_names([name], inplace=inplace)

@doc(
_shared_docs["to_replace"],
klass=_index_doc_kwargs["klass"],
inplace=_index_doc_kwargs["inplace"],
replace_iloc="",
)
def replace(
self,
to_replace=None,
value=None,
limit=None,
regex=False,
method="pad",
):
new_index = self.to_series().replace(
to_replace=to_replace, value=value, limit=limit, regex=regex, method=method
)
new_index = Index(new_index)

return new_index

# --------------------------------------------------------------------
# Level-Centric Methods

Expand Down
Loading