Vectorized String Methods (.str accessor)0%
Vectorized String Methods (.str accessor)
Beginner12 min read•Updated: Jul 11, 2026
Vectorized String Methods (.str accessor)
Reading Time: 8 Mins | Level: Beginner to Advanced
1. The Power of the .str Accessor
When working with textual data in Pandas, you do not need to write loops or apply() calls to clean strings. Pandas provides the specialized .str accessor, allowing you to execute string operations across entire columns simultaneously with built-in null-safety (automatically skipping NaN values without crashing).
2. Common Text Cleaning Operations
Python
import pandas as pd
df = pd.DataFrame({
'Raw_Name': [' amit sharma ', 'PRIYA VERMA', 'rohan kumar ', None],
'Email': ['amit.s@gmail.com', 'priya.v@yahoo.com', 'rohan.k@outlook.com', None],
'Phone': ['+91-98765-43210', '+91-87654-32109', '+91-76543-21098', None]
})
# 1. Stripping whitespace & changing case
df['Clean_Name'] = df['Raw_Name'].str.strip().str.title()
# 2. String replacement
df['Clean_Phone'] = df['Phone'].str.replace('+', '').str.replace('-', '')
# 3. String contains (pattern matching)
is_gmail = df['Email'].str.contains('gmail', case=False, na=False)
print("Gmail Users:\n", df[is_gmail])
3. Splitting Strings into Multiple Columns (expand=True)
When a column contains concatenated data (e.g. First_Name Last_Name or City, State):
Python
# Split Name into First and Last names
split_names = df['Clean_Name'].str.split(' ', expand=True)
split_names.columns = ['First_Name', 'Last_Name']
print(split_names)
Output:
Output
First_Name Last_Name
0 Amit Sharma
1 Priya Verma
2 Rohan Kumar
3 NaN NaN
4. Regular Expression (Regex) Extraction (.str.extract)
Extract specific patterns (such as email domains or pincodes) using regex capture groups:
Python
# Extract email domain using regex capture group
df['Domain'] = df['Email'].str.extract(r'@([\w\.]+)')
print(df[['Email', 'Domain']])
Interactive Quiz
Multiple Choice Questions
Question 1
Which accessor prefix is used to call vectorized string operations on a Pandas Series?
Question 2
What does setting
expand=True do in Series.str.split(',', expand=True)?Question 3
What does the
na=False argument achieve in Series.str.contains('keyword', na=False)?Question 4
Which method strips whitespace from both the beginning and end of every string in a Series?
Question 5
Which method uses regex capture groups
(...) to parse structured tokens into new DataFrame columns?Next Lesson
Renaming Columns, Replacing Values & Sorting
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Applying Custom Functions (apply, map, applymap) | Renaming Columns, Replacing Values & Sorting |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.