modin.pandas.Series.replace¶
- Series.replace(to_replace=None, value=_NoDefault.no_default, inplace=False, limit=None, regex=False, method: str | NoDefault = _NoDefault.no_default)[source]¶
Replace values given in to_replace with value.
Values of the DataFrame 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 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 optional value parameter should not be given.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 beNone
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 optional value parameter should not be specified 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) – Whether to modify the DataFrame rather than creating a new one.
limit (int, default None) – Maximum size gap to forward or backward fill. This parameter is not supported.
regex (bool or same types as to_replace, default False) – Whether to interpret to_replace and/or value as regular expressions. 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'}}) – The method to use when for replacement, when to_replace is a scalar, list or tuple and value is
None
. This parameter is not supported.
- Returns:
DataFrame Object after replacement if inplace=False, None otherwise.
- Return type:
- Raises:
AssertionError –
If regex is not a
bool
and to_replace is notNone
.
TypeError –
If to_replace is not a scalar, array-like,
dict
, orNone
* If to_replace is adict
and value is not alist
,dict
,ndarray
, orSeries
* If to_replace isNone
and regex is not compilable into a regular expression or is a list, dict, ndarray, or Series. * When replacing multiplebool
ordatetime64
objects and the arguments to to_replace does not match the type of the value being replaced
ValueError –
If a
list
or anndarray
is passed to to_replace and value but they are not the same length.
NotImplementedError –
If
method
orlimit
is provided.
Notes
Regex substitution is performed under the hood using snowflake backend. which supports POSIX ERE syntax for regular expressions. Please check usage notes for details. https://docs.snowflake.com/en/sql-reference/functions-regexp#general-usage-notes
Regular expressions only replace string values. If a regular expression is created to match floating point numbers, it will only match string data not numeric data.
This method has a lot of options. You are encouraged to experiment and play with this method to gain intuition about how it works.
Examples
Scalar `to_replace` and `value`
>>> s = pd.Series([1, 2, 3, 4, 5]) >>> s.replace(1, 5) 0 5 1 2 2 3 3 4 4 5 dtype: int64
dict-like `to_replace`
>>> s.replace({1: 10, 2: 100}) 0 10 1 100 2 3 3 4 4 5 dtype: int64
Regular expression `to_replace`
>>> s = pd.Series(['bat', 'foo', 'bait']) >>> s.replace(to_replace=r'^ba.$', value='new', regex=True) 0 new 1 foo 2 bait dtype: object
>>> s.replace(regex=r'^ba.$', value='new') 0 new 1 foo 2 bait dtype: object
>>> s.replace(regex={r'^ba.$': 'new', 'foo': 'xyz'}) 0 new 1 xyz 2 bait dtype: object
>>> s.replace(regex=[r'^ba.$', 'foo'], value='new') 0 new 1 new 2 bait dtype: object
Compare the behavior of
s.replace({{'a': None}})
ands.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 tos.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
On the other hand, if
None
is explicitly passed forvalue
, it will also be respected:>>> s.replace('a', None) 0 10 1 None 2 None 3 b 4 None dtype: object