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"
]
)
(
"Original Series:"
)
(
s
)
(
)
Convert to lowercase
(
"Convert to lowercase:"
)
(
s.
str
.
lower
(
)
)
(
)
Convert to uppercase
(
"Convert to uppercase:"
)
(
s.
str
.
upper
(
)
)
(
)
Capitalize the first letter
(
"Capitalize first letter:"
)
(
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"
]
)
(
"Original data:"
)
(
s
)
(
)
containment check
(
"contains 'python':"
)
(
s.
str
.
contains
(
"python"
,
case
=
False
)
)
(
)
Check Start/End
(
"starts with 'hello':"
)
(
s.
str
.
startswith
(
"hello"
)
)
(
)
Replacement
(
"Replace spaces with underscores:"
)
(
s.
str
.
replace
(
" "
,
"_"
)
)
(
)
Splitting
(
"Split by spaces:"
)
(
s.
str
.
split
(
" "
)
)
Trimming and Padding
Example
import
pandas
as
pd
s
=
pd.
Series
(
[
" hello "
,
"world "
,
" pandas"
,
" python "
]
)
(
"Original data:"
)
(
s
)
(
)
Remove leading and trailing spaces
(
"Strip leading and trailing spaces:"
)
(
s.
str
.
strip
(
)
)
(
)
Remove left spaces
(
"Remove left spaces:"
)
(
s.
str
.
lstrip
(
)
)
(
)
Remove right spaces
(
"Remove right spaces:"
)
(
s.
str
.
rstrip
(
)
)
(
)
Fill
(
"Pad left with 0 to length 10:"
)
(
s.
str
.
pad
(
10
,
side
=
"left"
,
fillchar
=
"0"
)
)
Slicing and Concatenation
Example
import
pandas
as
pd
s
=
pd.
Series
(
[
"hello"
,
"world"
,
"python"
,
"pandas"
]
)
(
"Original data:"
)
(
s
)
(
)
Slicing
(
"First 3 characters:"
)
(
s.
str
[
:
3
]
)
(
)
Take 3 starting from position 1
(
"Take 3 from position 1:"
)
(
s.
str
[
1
:
4
]
)
(
)
String concatenation
s1
=
pd.
Series
(
[
"Hello"
,
"World"
]
)
s2
=
pd.
Series
(
[
"Python"
,
"Pandas"
]
)
(
"Join using +:"
)
(
s1 +
" "
- s2
)
(
)
join concatenation (using a specified separator)
(
"join concatenation:"
)
(
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"
]
)
(
"Original data:"
)
(
s
)
(
)
Extract email addresses
(
"Extract username:"
)
(
s.
str
.
extract
(
r
"(\w+)@"
)
)
(
)
(
"Extract domain:"
)
(
s.
str
.
extract
(
r
"@(\w+.\w+)"
)
)
(
)
Replacement
(
"Replace email with [email]:"
)
(
s.
str
.
replace
(
r
"\w+@\w+.\w+"
,
"[email]"
,
regex
=
True
)
)
(
)
Contains Match
(
"contains .com or .org:"
)
(
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"
]
)
(
"Original data:"
)
(
s
)
(
)
Extract year, month, and day
extract_df
=
s.
str
.
extract
(
r
"(\d{4})-(\d{2})-(\d{2})"
)
extract_df.
columns
=
[
"year"
,
"month"
,
Sun
]
(
"Extract year, month, day:"
)
(
extract_df
)
(
)
Split by delimiter
s2
=
pd.
Series
(
[
"a,b,c"
,
"d,e,f"
,
"g,h,i"
]
)
(
"Split by comma:"
)
(
s2.
str
.
split
(
","
)
)
(
)
Split and expand into a DataFrame
(
"Split and expand:"
)
(
s2.
str
.
split
(
","
,
expand
=
True
)
)
Statistics and Conversion
Length and Counting
Example
import
pandas
as
pd
s
=
pd.
Series
(
[
"hello"
,
"world"
,
"python"
,
"pandas"
]
)
(
"Original data:"
)
(
s
)
(
)
String Length
(
"String length:"
)
(
s.
str
.
len
(
)
)
(
)
Character counting
s2
=
pd.
Series
(
[
"hello"
,
"world"
,
"aaa"
,
"bbb"
]
)
(
"Occurrences of 'l':"
)
(
s2.
str
.
count
(
"l"
)
)
Type Conversion
Example
import
pandas
as
pd
String to number
s
=
pd.
Series
(
[
"1"
,
"2"
,
"3"
,
"abc"
]
)
(
"String to number:"
)
(
pd.
to_numeric
(
s
,
errors
=
"coerce"
)
)
(
)
Convert Numbers to Strings
s2
=
pd.
Series
(
[
1
,
2
,
3
,
4
]
)
(
"Convert numbers to strings:"
)
(
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 "
]
}
)
(
"Original data:"
)
(
df
)
(
)
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
(
)
(
"After cleaning:"
)
(
df
)
(
)
2. Validate Data
(
"Email validation:"
)
(
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
.straccessor can efficiently accomplish most text processing tasks.