~/learn/Pandas · Cleaning data

Text and categorical columns

The .str accessor and ordered categories.

8 min readlesson 8 of 13strcategoryextract

why this matters

Names, emails, product codes and free text need cleaning before any analysis, and the .str accessor does it across a whole column at once.

The .str accessor applies string methods element-wise, vectorised and NaN-safe.

python · editable
loading editor…

Try it: Keep only the products whose name ends with 'r'.

str.split with expand=True turns one column into several, and str.extract pulls out a regex group.

python · editable
loading editor…

An ordered categorical gives text a meaningful sort order, so 'low, medium, high' no longer sorts alphabetically.

python · editable
loading editor…

Common gotcha

String methods live behind .str: use df['name'].str.lower(), not df['name'].lower().

Pro tip

Ordered categories let you sort Low < Medium < High correctly instead of alphabetically.

key takeaways

  • .str applies a string method to a whole column.
  • contains, split and strip cover most cleaning.
  • Ordered categories give text a meaningful sort order.

check your understanding

How do you lowercase every value in a text column?

free practice

Build confidence with a question you can solve without Pro.