← Back to Pandas Course | Chapter 5: Data Cleaning | Lesson 4 of 7

String cleaning

The .str accessor applies string methods to a whole column at once.

In this page:

  1. String cleaning
Syntax
python
df["column"].str.lower()
df["column"].str.strip()
df["column"].str.contains("text")

String cleaning

Access string methods through df["col"].str: lower, upper, strip, contains, startswith, len and more. They work on every value and skip missing ones. Regular expressions are supported in contains, replace and extract.

Note: str.title() capitalizes each word, handy for names.

Example: String cleaning

python
import pandas as pd

s = pd.Series(["  alice SMITH ", "BOB jones", None])
print(s.str.strip().str.title())
print(s.str.contains("bob", case=False))
print(s.str.len())

# Output:
# 0    Alice Smith
# 1      Bob Jones
# 2           None
# dtype: object
# 0    False
# 1     True
# 2     None
# dtype: object
# 0    14.0
# 1     9.0
# 2     NaN
# dtype: float64
Related Topics
Common Mistakes
  1. Calling string methods directly on the Series
  2. Ignoring NaN in text columns
  3. Forgetting str methods return new Series
Chapter Summary
  • Use the .str accessor
  • Methods run on every value
  • NaN is skipped safely
  • Regex is supported
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.