Pandas Series str | replace method
Start your free 7-days trial now!
Pandas Series str.replace(~) method replaces a substring of each string in the Series with a specified value. This operation is not done inplace, meaning a new Series is returned and the original is kept intact.
Parameters
1. pat | string or regex
The substring to replace. Since regex=True by default, pat will be treated as a regular expression.
2. repl | string or callable
The value to replace pat. If a callable is passed, then it takes as argument the matched regex pattern and returns a string that replaces the match.
3. n | int | optional
The maximum number (inclusive) of replacements to make. By default, there is no limit as to how many replacements are made.
4. case | boolean or None | optional
Whether or not the matching is to be case-sensitive:
Value | Description |
|---|---|
| Matching is case sensitive. |
| Matching is not case sensitive. |
| The case when regex is used. |
By default, case=None (since regex=True by default). Note that case cannot be set if pat is a compiled regex.
5. flags | int | optional
The flags found in the standard regex module (e.g. re.IGNORECASE). By default, flags=0. Note that flags cannot be set if pat is a compiled regular expression.
6. regex | boolean | optional
Whether or not pat is to be treated as a regular expression. By default, regex=True.
Return Value
A new Series with the replaced substrings.
Examples
Basic usage
To replace the substring "A" with "c" for each string in the Series:
Using regex
By default, regex=True, which means that you can directly pass in a regular expression like so:
Here, we are replacing substrings that end with A.
Using compiled regex
To use a compiled regex instead of a regex in string form:
import remy_regex = re.compile("a", flags=re.IGNORECASE)s.str.replace(my_regex, "D")
0 DD1 bD2 Dcdtype: object
Passing in a callable for repl
The function that you pass to repl is given one argument - the regex object that captures the match. This function must return a string that will replace the match.
For instance, consider the following:
def foo(my_regex): match = my_regex.group(0) return match.upper()
s.str.replace(".*A$", foo)
0 AA1 BA2 Acdtype: object
Here, we are replacing every string that ends with A by its uppercase form. Just to clarify, foo is called twice in this case and if we were to print the value of match, we would see the following:
aAbA