String Cleaning
Replace Substring
Swap a specific token inside every string in a column. By hand, call
s.replace(old, new) on each element. With pandas, Series.str.replace (old, new, regex=False) applies the literal substitution column-wide.
By hand
With pandas
df['x'].str.replace('St.', 'Street', regex=False) performs the same
literal substitution on every element. regex=False makes the pattern
a plain string — the default in pinned pandas, but explicit here because
'St.' contains a dot that would match any character as a regex.
naive.py
strings = ['Oak St.', 'Pine St.', 'Elm Ave', 'Maple St.', 'Cedar Ave']
result = []
for s in strings:
result.append(s.replace('St.', 'Street'))
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
strings = ['Oak St.', 'Pine St.', 'Elm Ave', 'Maple St.', 'Cedar Ave']
df = pd.DataFrame({'x': strings})
s = df['x'].str.replace('St.', 'Street', regex=False)
result = s.tolist()
print('index:', s.index.tolist())
print('dtype:', s.dtype)
print('values:', s.tolist())
print('RESULT:', result)
index: [0, 1, 2, 3, 4]
dtype: object
values: ['Oak Street', 'Pine Street', 'Elm Ave', 'Maple Street', 'Cedar Ave']
RESULT: ['Oak Street', 'Pine Street', 'Elm Ave', 'Maple Street', 'Cedar Ave']
Implementation notes
regex=Falseis the default and treats the pattern as a literal string. Passregex=Trueonly when you need a regex pattern (e.g. a character class or quantifier).- Python's
str.replacereplaces every non-overlapping occurrence within each string, as does the pandas accessor — not just the first one. - Cross-reference:
parse-formatted-numbers(ch02) for the same.str.replacepattern applied before a numeric cast.