TExcelTAD
Home › pandas › String Methods (.str)

String Methods (.str)

Text columns are everywhere: names, emails, product codes, addresses. Python strings have handy methods like .upper() and .split(), and pandas makes all of them available for a whole column at once through the .str accessor. Missing values are skipped automatically instead of causing errors.

Basic transformations

python · try it yourself
import pandas as pd

names = pd.Series(["  ada LOVELACE", "grace hopper ", "Alan Turing", None])
print(names.str.strip())
print(names.str.strip().str.title())
print(names.str.len())
0    ada LOVELACE
1    grace hopper
2     Alan Turing
3            None
dtype: object
0    Ada Lovelace
1    Grace Hopper
2     Alan Turing
3            None
dtype: object
0    14.0
1    13.0
2    11.0
3     NaN
dtype: float64

Methods can be chained: .str.strip().str.title() first trims the spaces, then capitalises each word. The None passes through as a missing value.

Method Does
lower(), upper(), title(), capitalize() change case
strip(), lstrip(), rstrip() remove surrounding whitespace (or given characters)
len() length of each string
replace(old, new) replace text (regex optional)
contains(pat), startswith(), endswith() test → boolean mask
split(sep), get(i) split into lists, pick an element
slice(start, stop) or .str[0:3] substring
extract(regex) capture groups → columns
pad(), zfill() pad to a width
cat() concatenate

Testing text: contains, startswith, endswith

These return boolean masks, so they plug straight into filtering:

python · try it yourself
import pandas as pd

emails = pd.DataFrame({
    "user": ["noah", "lia", "tom", "eva", "sam"],
    "email": ["noah@shop.com", "lia@gmail.com", "tom@shop.com", "eva@uni.edu", "sam@Shop.com"],
})
staff = emails["email"].str.lower().str.endswith("@shop.com")
print(emails[staff])
print(emails["email"].str.contains("gmail|uni", regex=True).sum())
   user          email
0  noah  noah@shop.com
2   tom   tom@shop.com
4   sam   sam@Shop.com
2

contains treats the pattern as a regular expression by default, so "gmail|uni" means "gmail or uni". Pass regex=False to match text literally (important for characters like . or $).

Splitting into columns

split() returns a list per row. Add expand=True to spread the parts across columns:

python · try it yourself
import pandas as pd

people = pd.DataFrame({"full_name": ["Lovelace, Ada", "Hopper, Grace", "Turing, Alan"]})
parts = people["full_name"].str.split(", ", expand=True)
people["last"] = parts[0]
people["first"] = parts[1]
print(people)

codes = pd.Series(["EU-DE-0042", "US-CA-0007", "AS-JP-0110"])
print(codes.str.split("-").str[1].to_list())
       full_name      last  first
0  Lovelace, Ada  Lovelace    Ada
1  Hopper, Grace    Hopper  Grace
2   Turing, Alan    Turing   Alan
['DE', 'CA', 'JP']

.str[1] on a column of lists picks the element at position 1 of each list. The same indexing works on strings: .str[:2] gives the first two characters.

Extracting with regular expressions

extract() pulls out the parts matched by capture groups (parentheses) in a regex. Named groups (?P<name>...) become column names:

python · try it yourself
import pandas as pd

log = pd.Series([
    "2024-05-01 ERROR disk full (code 507)",
    "2024-05-01 INFO backup done",
    "2024-05-02 WARN slow response (code 299)",
])
parts = log.str.extract(r"(?P<date>\S+) (?P<level>[A-Z]+) (?P<message>.*)")
print(parts)
print(log.str.extract(r"code (\d+)")[0].to_list())
         date  level                   message
0  2024-05-01  ERROR      disk full (code 507)
1  2024-05-01   INFO               backup done
2  2024-05-02   WARN  slow response (code 299)
['507', nan, '299']

Rows without a match get NaN.

Replacing and cleaning

python · try it yourself
import pandas as pd

phones = pd.Series(["(030) 555-0101", "030.555.0199", "030 555 0123"])
digits = phones.str.replace(r"\D", "", regex=True)
print(digits.to_list())

ids = pd.Series([7, 42, 315]).astype(str)
print(ids.str.zfill(5).to_list())
print(("INV-" + ids.str.zfill(5)).to_list())
['0305550101', '0305550199', '0305550123']
['00007', '00042', '00315']
['INV-00007', 'INV-00042', 'INV-00315']

\D means "any character that isn't a digit", so the replacement removes everything but the numbers. + concatenates string columns element by element.

Tip: Text methods are much faster and clearer than apply(lambda s: ...) with Python string code, and they handle missing values for you.

Test yourself

How do you make every value in the city column upper case?

  1. df["city"].upper()
  2. df["city"].str.upper()
  3. upper(df["city"])
  4. df.upper("city")

What does split("-", expand=True) return?

  1. A Series of lists
  2. A DataFrame with one column per part
  3. The number of parts
  4. The first part only

By default, how does str.contains("a.c") treat the dot?

  1. As a literal dot
  2. As a regex wildcard matching any character
  3. As a separator
  4. It raises an error