pandas 1.4.2

NotesParametersRaisesReturns
replace(self, pat: 'str | re.Pattern', repl: 'str | Callable', n: 'int' = -1, case: 'bool | None' = None, flags: 'int' = 0, regex: 'bool | None' = None)

Equivalent to str.replace or re.sub , depending on the regex value.

Notes

When :None:None:`pat` is a compiled regex, all flags should be included in the compiled regex. Use of :None:None:`case`, flags , or :None:None:`regex=False` with a compiled regex will raise an error.

Parameters

pat : str or compiled regex

String can be a character sequence or regular expression.

repl : str or callable

Replacement string or a callable. The callable is passed the regex match object and must return a replacement string to be used. See re.sub .

n : int, default -1 (all)

Number of replacements to make from start.

case : bool, default None

Determines if replace is case sensitive:

  • If True, case sensitive (the default if :None:None:`pat` is a string)

  • Set to False for case insensitive

  • Cannot be set if :None:None:`pat` is a compiled regex.

flags : int, default 0 (no flags)

Regex module flags, e.g. re.IGNORECASE. Cannot be set if :None:None:`pat` is a compiled regex.

regex : bool, default True

Determines if the passed-in pattern is a regular expression:

  • If True, assumes the passed-in pattern is a regular expression.

  • If False, treats the pattern as a literal string

  • Cannot be set to False if :None:None:`pat` is a compiled regex or :None:None:`repl` is a callable.

versionadded

Raises

ValueError
  • if regex is False and :None:None:`repl` is a callable or :None:None:`pat` is a compiled regex

  • if :None:None:`pat` is a compiled regex and :None:None:`case` or flags is set

Returns

Series or Index of object

A copy of the object with all matching occurrences of :None:None:`pat` replaced by :None:None:`repl`.

Replace each occurrence of pattern/regex in the Series/Index.

Examples

When :None:None:`pat` is a string and regex is True (the default), the given :None:None:`pat` is compiled as a regex. When :None:None:`repl` is a string, it replaces matching regex patterns as with re.sub . NaN value(s) in the Series are left as is:

This example is valid syntax, but we were not able to check execution
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f.', 'ba', regex=True)
0    bao
1    baz
2    NaN
dtype: object

When :None:None:`pat` is a string and regex is False, every :None:None:`pat` is replaced with :None:None:`repl` as with str.replace :

This example is valid syntax, but we were not able to check execution
>>> pd.Series(['f.o', 'fuz', np.nan]).str.replace('f.', 'ba', regex=False)
0    bao
1    fuz
2    NaN
dtype: object

When :None:None:`repl` is a callable, it is called on every :None:None:`pat` using re.sub . The callable should expect one positional argument (a regex object) and return a string.

To get the idea:

This example is valid syntax, but we were not able to check execution
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f', repr, regex=True)
0    <re.Match object; span=(0, 1), match='f'>oo
1    <re.Match object; span=(0, 1), match='f'>uz
2                                            NaN
dtype: object

Reverse every lowercase alphabetic word:

This example is valid syntax, but we were not able to check execution
>>> repl = lambda m: m.group(0)[::-1]
... ser = pd.Series(['foo 123', 'bar baz', np.nan])
... ser.str.replace(r'[a-z]+', repl, regex=True) 0 oof 123 1 rab zab 2 NaN dtype: object

Using regex groups (extract second group and swap case):

This example is valid syntax, but we were not able to check execution
>>> pat = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)"
... repl = lambda m: m.group('two').swapcase()
... ser = pd.Series(['One Two Three', 'Foo Bar Baz'])
... ser.str.replace(pat, repl, regex=True) 0 tWO 1 bAR dtype: object

Using a compiled regex with flags

This example is valid syntax, but we were not able to check execution
>>> import re
... regex_pat = re.compile(r'FUZ', flags=re.IGNORECASE)
... pd.Series(['foo', 'fuz', np.nan]).str.replace(regex_pat, 'bar', regex=True) 0 foo 1 bar 2 NaN dtype: object
See :

Local connectivity graph

Hover to see nodes names; edges to Self not shown, Caped at 50 nodes.

Using a canvas is more power efficient and can get hundred of nodes ; but does not allow hyperlinks; , arrows or text (beyond on hover)

SVG is more flexible but power hungry; and does not scale well to 50 + nodes.

All aboves nodes referred to, (or are referred from) current nodes; Edges from Self to other have been omitted (or all nodes would be connected to the central node "self" which is not useful). Nodes are colored by the library they belong to, and scaled with the number of references pointing them


File: /pandas/core/strings/accessor.py#1290
type: <class 'function'>
Commit: