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

Pandas String Operations

Pandas String Operations

Pandas provides powerful string processing capabilities; through the .str accessor you can process each element in a Series just like a Python string.


Overview of the str Accessor

When the data type of a Series is object , you can use the .str accessor for string operations.

Example

import

pandas

as

pd

Create a Series containing strings

s

=

pd.

Series

(

[

"hello"

,

"world"

,

"pandas"

,

"Python"

]

)

print

(

"Original Series:"

)

print

(

s

)

print

(

)

Convert to lowercase

print

(

"Convert to lowercase:"

)

print

(

s.

str

.

lower

(

)

)

print

(

)

Convert to uppercase

print

(

"Convert to uppercase:"

)

print

(

s.

str

.

upper

(

)

)

print

(

)

Capitalize the first letter

print

(

"Capitalize first letter:"

)

print

(

s.

str

.

capitalize

(

)

)


Common String Functions

Case Conversion

Method Description Example
str.lower() Lowercase conversion "Hello" → "hello"
str.upper() Convert to uppercase "Hello" → "HELLO"
str.title() Capitalize the first letter "hello world" → "Hello World"
str.capitalize() Capitalize the first letter and lowercase the rest "hELLO" → "Hello"
str.swapcase() Swap case "HeLLo" → "hEllO"

String Search and Replacement

Example

import

pandas

as

pd

s

=

pd.

Series

(

[

"hello world"

,

"python pandas"

,

"data science"

,

"machine learning"

]

)

print

(

"Original data:"

)

print

(

s

)

print

(

)

containment check

print

(

"contains 'python':"

)

print

(

s.

str

.

contains

(

"python"

,

case

=

False

)

)

print

(

)

Check Start/End

print

(

"starts with 'hello':"

)

print

(

s.

str

.

startswith

(

"hello"

)

)

print

(

)

Replacement

print

(

"Replace spaces with underscores:"

)

print

(

s.

str

.

replace

(

" "

,

"_"

)

)

print

(

)

Splitting

print

(

"Split by spaces:"

)

print

(

s.

str

.

split

(

" "

)

)

Trimming and Padding

Example

import

pandas

as

pd

s

=

pd.

Series

(

[

"  hello  "

,

"world  "

,

"  pandas"

,

" python "

]

)

print

(

"Original data:"

)

print

(

s

)

print

(

)

Remove leading and trailing spaces

print

(

"Strip leading and trailing spaces:"

)

print

(

s.

str

.

strip

(

)

)

print

(

)

Remove left spaces

print

(

"Remove left spaces:"

)

print

(

s.

str

.

lstrip

(

)

)

print

(

)

Remove right spaces

print

(

"Remove right spaces:"

)

print

(

s.

str

.

rstrip

(

)

)

print

(

)

Fill

print

(

"Pad left with 0 to length 10:"

)

print

(

s.

str

.

pad

(

10

,

side

=

"left"

,

fillchar

=

"0"

)

)


Slicing and Concatenation

Example

import

pandas

as

pd

s

=

pd.

Series

(

[

"hello"

,

"world"

,

"python"

,

"pandas"

]

)

print

(

"Original data:"

)

print

(

s

)

print

(

)

Slicing

print

(

"First 3 characters:"

)

print

(

s.

str

[

:

3

]

)

print

(

)

Take 3 starting from position 1

print

(

"Take 3 from position 1:"

)

print

(

s.

str

[

1

:

4

]

)

print

(

)

String concatenation

s1

=

pd.

Series

(

[

"Hello"

,

"World"

]

)

s2

=

pd.

Series

(

[

"Python"

,

"Pandas"

]

)

print

(

"Join using +:"

)

print

(

s1 +

" "

)

print

(

)

join concatenation (using a specified separator)

print

(

"join concatenation:"

)

print

(

s1.

str

.

cat

(

s2

,

sep

=

"-"

)

)


Regular Expression Support

Pandas' string functions support regular expressions, a powerful tool for handling complex string patterns.

Example

import

pandas

as

pd

s

=

pd.

Series

(

[

   

"user@example.com"

,

   

"test@domain.org"

,

   

"invalid-email"

,

   

"admin@site.net"

]

)

print

(

"Original data:"

)

print

(

s

)

print

(

)

Extract email addresses

print

(

"Extract username:"

)

print

(

s.

str

.

extract

(

r

"(\w+)@"

)

)

print

(

)

print

(

"Extract domain:"

)

print

(

s.

str

.

extract

(

r

"@(\w+.\w+)"

)

)

print

(

)

Replacement

print

(

"Replace email with [email]:"

)

print

(

s.

str

.

replace

(

r

"\w+@\w+.\w+"

,

"[email]"

,

regex

=

True

)

)

print

(

)

Contains Match

print

(

"contains .com or .org:"

)

print

(

s.

str

.

contains

(

r

".com|.org"

)

)

Extraction and Splitting

Example

import

pandas

as

pd

s

=

pd.

Series

(

[

"2024-01-01"

,

"2024-02-15"

,

"2024-03-20"

]

)

print

(

"Original data:"

)

print

(

s

)

print

(

)

Extract year, month, and day

extract_df

=

s.

str

.

extract

(

r

"(\d{4})-(\d{2})-(\d{2})"

)

extract_df.

columns

=

[

"year"

,

"month"

,

Sun

]

print

(

"Extract year, month, day:"

)

print

(

extract_df

)

print

(

)

Split by delimiter

s2

=

pd.

Series

(

[

"a,b,c"

,

"d,e,f"

,

"g,h,i"

]

)

print

(

"Split by comma:"

)

print

(

s2.

str

.

split

(

","

)

)

print

(

)

Split and expand into a DataFrame

print

(

"Split and expand:"

)

print

(

s2.

str

.

split

(

","

,

expand

=

True

)

)


Statistics and Conversion

Length and Counting

Example

import

pandas

as

pd

s

=

pd.

Series

(

[

"hello"

,

"world"

,

"python"

,

"pandas"

]

)

print

(

"Original data:"

)

print

(

s

)

print

(

)

String Length

print

(

"String length:"

)

print

(

s.

str

.

len

(

)

)

print

(

)

Character counting

s2

=

pd.

Series

(

[

"hello"

,

"world"

,

"aaa"

,

"bbb"

]

)

print

(

"Occurrences of 'l':"

)

print

(

s2.

str

.

count

(

"l"

)

)

Type Conversion

Example

import

pandas

as

pd

String to number

s

=

pd.

Series

(

[

"1"

,

"2"

,

"3"

,

"abc"

]

)

print

(

"String to number:"

)

print

(

pd.

to_numeric

(

s

,

errors

=

"coerce"

)

)

print

(

)

Convert Numbers to Strings

s2

=

pd.

Series

(

[

1

,

2

,

3

,

4

]

)

print

(

"Convert numbers to strings:"

)

print

(

s2.

astype

(

str

)

.

str

.

zfill

(

4

)

)

 

Zero-pad to 4 digits


Practical example: data cleaning

Example

import

pandas

as

pd

import

numpy

as

np

Simulate Dirty Data

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

" Zhang San "

,

"Li Si"

,

"Wang Wu "

]

,

   

"Phone"

:

[

"138-0000-0000"

,

"13900000000"

,

"  010-12345678  "

]

,

   

"email"

:

[

"zhangsan@email.com"

,

"LISI@EMAIL.COM"

,

"wang.wu@domain.com "

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Cleaning steps

1. Remove Spaces

df

[

"Name"

]

=

df

[

"Name"

]

.

str

.

strip

(

)

df

[

"Phone"

]

=

df

[

"Phone"

]

.

str

.

replace

(

"-"

,

""

)

.

str

.

strip

(

)

df

[

"email"

]

=

df

[

"email"

]

.

str

.

strip

(

)

.

str

.

lower

(

)

print

(

"After cleaning:"

)

print

(

df

)

print

(

)

2. Validate Data

print

(

"Email validation:"

)

print

(

df

[

"email"

]

.

str

.

contains

(

r

"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$"

)

)


Notes

1. Handling Missing Values

String operations skip missing values (NaN) by default; if you need to handle them, you can use .fillna() to fill them first.

2. Case Sensitivity

Most functions are case-sensitive by default; use the case=False parameter to perform case-insensitive matching.

3. Regular Expression Performance

Regular expressions are powerful but relatively slow; pay attention to performance when processing large amounts of data.

String processing is an important part of data cleaning; reasonable use of the .str accessor can efficiently accomplish most text processing tasks.