Skip to the workspace
Pebellslearn by building
Cleaning Data  ›  Lesson

Cleaning Text Columns

Pandas String Methods 14 minThe .str accessor applies string methods such as strip, title, replace, split and extract to every value in a column, folding messy spellings into clean categories.

python data analysis / Cleaning Text Columns

Explore each scene at your own pace.

01 · The rule

The rule

Cleaning Text Columns

Three branches, but the export's branch column claims seven different values. Clerks typed " Pune", "pune" and "Pune ", and to a computer those are three different cities. A groupby on this column would split Pune's sales into three piles. Text needs cleaning before it can be a key.

The rule

.str applies a string method to every value at once.

Here is the messy column from a new export, messy:

messy["branch"].tolist()
# [' Pune', 'delhi', 'Pune ', 'CHENNAI', 'Delhi', 'chennai', 'pune', 'Delhi']
messy["branch"].nunique()   # 7

Every Python string method you know has a column-wide twin behind .str:

messy["branch"] = messy["branch"].str.strip().str.title()
messy["branch"].nunique()   # 3: Pune, Delhi, Chennai

strip() removes spaces from both ends; title() capitalises each word. Chained, they fold all seven spellings into three. lower() and upper() work too; pick one style and use it everywhere.

Other everyday cleaners:

# price arrives as text like "₹250"
messy["price"] = messy["price"].str.replace("₹", "").astype(int)

# genre arrives as "fiction/novel"; keep the part before the slash
messy["genre"] = messy["genre"].str.split("/").str[0]

# find rows by text
messy[messy["genre"].str.contains("sci")]

.str.split() gives a list per row, and .str[0] then picks the first item of each list.

For patterns, .str methods accept regular expressions (Python's re language for describing text shapes). To pull the number out of labels like "Order #1042":

orders["code"].str.extract(r"(\d+)")   # a column holding '1042'

\d+ means "one or more digits", and the parentheses mark the part to keep.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.