Examples
When pat is a string and regex is True (the default), the given pat is compiled as a regex.
When repl is a string, it replaces matching regex patterns as with re.sub(). NaN value(s)
in the Series are left as is:
import numpy as np
import pandas as pd
pd.Series(['full', 'fog', np.nan]).str.replace('f.', 'bu', regex=True)
When pat is a string and regex is False, every pat is replaced with repl
as with str.replace():
pd.Series(['f.n', 'fog', np.nan]).str.replace('f.', 'bu', regex=False)
When repl is a callable, it is called on every pat using re.sub(). The callable should expect
one positional argument (a regex object) and return a string.
To get the idea:
pd.Series(['full', 'fog', np.nan]).str.replace('f', repr)
Reverse every lowercase alphabetic word:
repl = lambda m: m.group(0)[::-1]
pd.Series(['full 234', 'brr bzz', np.nan]).str.replace(r'[a-z]+', repl)
Using regex groups (extract second group and swap case):
pat = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)"
repl = lambda m: m.group('two').swapcase()
pd.Series(['One Two Three', 'Full Brr Bzz']).str.replace(pat, repl)
Using a compiled regex with flags
import re
regex_pat = re.compile(r'FOG', flags=re.IGNORECASE)
pd.Series(['full', 'fog', np.nan]).str.replace(regex_pat, 'brr')