Pandas Series.str.replace() function
Series.str.replace() is a function in Pandas used to replace specified content in strings.
During data processing, we often need to perform text replacement, such as fixing incorrect text, standardizing data formats, and removing unwanted characters.replace() The function can flexibly replace specified content in strings and supports regular expression matching.
Word meaning:replace means "to replace", indicating replacing old content with new content.
Basic syntax and parameters
str.replace() is a string accessor method of Series, so you need a Series containing strings first, and then call it through the .str accessor.
Syntax format
Series.str.replace(pat, repl, regex=False)
Parameter Description
| Parameters | Type | Required | Description | Default value |
|---|---|---|---|---|
| pat | str or regex | Required | The pattern to replace; can be a plain string or a regular expression (when regex=True). | - |
| repl | str or callable | Required | The replacement content; can be a string or a callable (for advanced replacement). | - |
| regex | bool | Optional | Whether to treat the pat parameter as a regular expression. Defaults to False. | False |
Function description
- Return Value: Returns a new Series after replacement.
- effect: Replaces matched content in each string element of the Series with new content.
- Note: By default, plain string matching is used; if regular expression matching is needed, set
regex=True。
Example
Let us thoroughly master str.replace() through a series of examples from simple to complex.
Example 1: Basic Usage - Simple String Replacement
Example
import
pandas
as
pd
Create a Series containing text
s
=
pd.
Series
(
[
'apple'
,
'banana'
,
'apricot'
,
'pineapple'
]
)
Replace 'ap' with 'XX'
result
=
s.
str
.
replace
(
'ap'
,
'XX'
)
(
"Original Series:"
)
(
s
)
(
"nReplaced result:"
)
(
result
)
Output result:
原始 Series:
0 apple
1 banana
2 apricot
3 pineapple
dtype: object
Replaced result:
0 XXle
1 banana
2 XXricot
3 XXneXXple
Code analysis:
s.str.replace('ap', 'XX')Replaces all occurrences of 'ap' with 'XX'.- By default, only the first match is replaced (if a string contains multiple occurrences, only the first is replaced).
- You can replace all matches by adding a regular expression flag.
Example 2: Replacing All Matches with a Regular Expression
When you need to replace all matches, you can use a regular expression.
Example
import
pandas
as
pd
Create a Series containing text
s
=
pd.
Series
(
[
'apple'
,
'banana'
,
'apricot'
,
'pineapple'
]
)
Use a regular expression to replace all 'ap' with 'XX'
result
=
s.
str
.
replace
(
'ap'
,
'XX'
,
regex
=
True
)
(
"Original Series:"
)
(
s
)
(
"nResult after replacing all 'ap':"
)
(
result
)
Output result:
原始 Series:
0 apple
1 banana
2 apricot
3 pineapple
dtype: object
Replace all results after 'ap':
0 XXle
1 banana
2 XXricot
3 XXneXXple
Code analysis:
- Settings
regex=TrueAfter enabling it, a regular expression is used for matching. - In regular expressions,
'ap'Matches all occurrences of 'ap' in the string. - 'pineapple' contains two 'ap's, and both are replaced with 'XX'.
Example 3: Replacing Digits and Symbols
replace() It can be used to clean data, such as removing digits or special symbols.
Example
import
pandas
as
pd
Create a Series with mixed content
s
=
pd.
Series
(
[
'phone: 123-456-7890'
,
'price: $99.99'
,
'date: 2024-01-01'
]
)
Remove all digits
result_digits
=
s.
str
.
replace
(
r
'd'
,
''
,
regex
=
True
)
Remove all non-alphanumeric characters (keep spaces)
result_special
=
s.
str
.
replace
(
r
'[^a-zA-Z0-9s]'
,
''
,
regex
=
True
)
(
"Original Series:"
)
(
s
)
(
"nAfter removing all digits:"
)
(
result_digits
)
(
"nAfter removing all special characters:"
)
(
result_special
)
Output result:
原始 Series:
0 phone: 123-456-7890
1 price: $99.99
2 date: 2024-01-01
dtype: object
After removing all numbers:
phone: ---
price: $.$
date: ------
After removing all special characters:
phone 1234567890
price 9999
date 20240101
Code analysis:
r'd'is a regular expression matching any digit.r'[^a-zA-Z0-9s]'Matches all characters that are not alphanumeric and not spaces.- This is a very common operation in data cleaning.
Example 4: Replacing Using a Callback Function
repl The parameter can be a function for more complex replacement logic.
Example
import
pandas
as
pd
Create a Series containing text
s
=
pd.
Series
(
[
'hello'
,
'world'
,
'runoob'
,
'python'
]
)
Use a callback function to convert matched strings to uppercase
result
=
s.
str
.
replace
(
r
'[aeiou]'
,
lambda
m: m.
group
(
0
)
.
upper
(
)
,
regex
=
True
)
(
"Original Series:"
)
(
s
)
(
"nAfter converting vowels to uppercase:"
)
(
result
)
Output result:
原始 Series:
0 hello
1 world
2 runoob
3 python
dtype: object
After converting vowels to uppercase:
0 hEllo
1 wOrld
2 rUnOOb
3 pythOn
Code analysis:
- The callback function receives a match object and can use
m.group(0)to obtain the matched content. - Converts vowels (a, e, i, o, u) to uppercase.
- This is a good way to implement more complex replacement logic.
Example 5: Standardizing Data Formats
In real projects,replace() It is often used to standardize data formats.
Example
import
pandas
as
pd
Simulate user-entered country names (inconsistent formats)
countries
=
pd.
Series
(
[
'USA'
,
'U.S.A.'
,
'U.S.A'
,
'usa'
,
'us'
,
'United States'
]
)
Replace with standardized names uniformly
result
=
countries.
replace
(
{
'USA'
:
'US'
,
'U.S.A.'
:
'US'
,
'U.S.A'
:
'US'
,
'usa'
:
'US'
,
'us'
:
'US'
,
'United States'
:
'US'
}
)
(
"Original country names:"
)
(
countries
)
(
"nStandardized result:"
)
(
result
)
Output result:
原始国家名称:
0 USA
1 U.S.A.
2 U.S.A
3 usa
4 us
5 United States
dtype:
object
Unified results:
0 US
1 US
2 US
3 US
4 0 US
dtype: object
Code analysis:
- This example uses the Series
replace()method (not str.replace). - You can pass a dictionary to replace multiple values in bulk.
- Unifies various different representations into a standard format.
Notes
- By default (
regex=False),patThe parameter is treated as a plain string, replacing only the first match. - Settings
regex=TrueAfter that, a regular expression is used for matching, allowing all matches to be replaced. - Some special characters in regular expressions (such as
.、*, etc.) need to be escaped. - If the Series contains NaN values,
replace()NaN is returned. - This function returns a new Series and does not modify the original data.
Common Pandas functions