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 pdlistings = 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())
.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.
.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”.