How do I clean text columns in pandas with .str?

Strip spaces and upper-case tickers with .str.strip() and .str.upper(), remove an exchange suffix with .str.removesuffix(), see why .str.replace() can remove more than intended, and find company names with .str.contains().

After this lesson, you can clean a vendor’s tickers before a merge and find companies by part of their name.

How do I clean spaces and capital letters?

.str applies text operations to every row of a column, so .str.strip() removes the spaces around each ticker and .str.upper() turns it into capital letters. A ticker received as "BBB " matches "BBB" only after the strip.

The listings are five made-up stocks, with the ticker as the vendor sent it, the company name and a close in kronor. None marks a missing name.

The following box cleans the tickers.

import pandas as pd

listings = pd.DataFrame({
    "vendor_ticker": [" aaa.ST", "BBB ", "ccc.STX", "FASTCO", "eee "],
    "name": ["AAA Holdings Inc.", "BBB Bank AB", "CCC Energy Inc", None, "EEE bank Corp."],
    "close": [101.2, 55.1, 230.0, 74.3, 18.9],
})
listings["clean_ticker"] = listings["vendor_ticker"].str.strip().str.upper()
print(listings[["vendor_ticker", "clean_ticker"]])
print((listings["vendor_ticker"] == "BBB").sum(), (listings["clean_ticker"] == "BBB").sum())
  vendor_ticker clean_ticker
0        aaa.ST       AAA.ST
1          BBB           BBB
2       ccc.STX      CCC.STX
3        FASTCO       FASTCO
4          eee           EEE
0 1

How do I remove an exchange suffix?

.str.removesuffix(".ST") removes .ST only at the end of a ticker, so AAA.ST becomes AAA and FASTCO and CCC.STX stay as they are. .str.replace(".ST", "", regex=True) removes every match anywhere, and as a regular expression the dot matches any character, so FASTCO loses AST and becomes FCO.

regex=False makes the dot an ordinary character, but .str.replace still removes .ST from the middle of CCC.STX.

The following box compares the three ways.

listings["ticker"] = listings["clean_ticker"].str.removesuffix(".ST")
print(pd.DataFrame({
    "pattern": listings["clean_ticker"].str.replace(".ST", "", regex=True),
    "literal": listings["clean_ticker"].str.replace(".ST", "", regex=False),
    "suffix": listings["ticker"],
}))
  pattern literal   suffix
0     AAA     AAA      AAA
1     BBB     BBB      BBB
2    CCCX    CCCX  CCC.STX
3     FCO  FASTCO   FASTCO
4     EEE     EEE      EEE

How do I find part of a company name?

.str.contains("bank", case=False, regex=False, na=False) marks the names that contain “bank” in any case, here BBB Bank AB and EEE bank Corp. regex=False searches for plain text, case=False ignores capital letters, and na=False marks a missing name as no match.

.loc[mask, columns] keeps the marked rows, as in the lesson on selecting rows. The search also matches inside longer words, such as “Bankruptcy”.

The following box finds the banks.

banks = listings["name"].str.contains("bank", case=False, regex=False, na=False)
print(listings.loc[banks, ["ticker", "name"]])
  ticker            name
1    BBB     BBB Bank AB
4    EEE  EEE bank Corp.

Your turn

Count the names that contain Inc with that capitalisation. You should see 2.

Without case=False, the search keeps the capital I.

print(listings["name"].str.contains("Inc", regex=False, na=False).sum())
2