Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Series.str.replace() function

Pandas Series.str.replace() function

Pandas Common Functions Common Pandas functions


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


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'

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nReplaced result:"

)

print

(

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:

  1. s.str.replace('ap', 'XX') Replaces all occurrences of 'ap' with 'XX'.
  2. By default, only the first match is replaced (if a string contains multiple occurrences, only the first is replaced).
  3. 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

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nResult after replacing all 'ap':"

)

print

(

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:

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

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nAfter removing all digits:"

)

print

(

result_digits

)

print

(

"nAfter removing all special characters:"

)

print

(

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:

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

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nAfter converting vowels to uppercase:"

)

print

(

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:

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'

}

)

print

(

"Original country names:"

)

print

(

countries

)

print

(

"nStandardized result:"

)

print

(

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:


Notes


Pandas Common Functions Common Pandas functions