String Cleaning
Normalize Case
Fold a column of mixed-case strings to a consistent case for matching and
grouping. By hand, call s.lower() on each element. With pandas,
Series.str.lower() applies the lowercasing across the entire column.
By hand
With pandas
df['x'].str.lower() returns a new object Series with every string
lowercased. The dtype is unchanged. The snapshot confirms all values are
now lowercase.
naive.py
names = ['Alice', 'BOB', 'carol', 'DAVE', 'Eve']
result = []
for s in names:
result.append(s.lower())
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
names = ['Alice', 'BOB', 'carol', 'DAVE', 'Eve']
df = pd.DataFrame({'x': names})
s = df['x'].str.lower()
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: ['alice', 'bob', 'carol', 'dave', 'eve']
RESULT: ['alice', 'bob', 'carol', 'dave', 'eve']
Implementation notes
.lower()is the most common normalization for lookups and groupby keys. Use.upper()for uppercase or.title()for Title Case (first letter of each word capitalized).- Case normalization is usually applied after stripping whitespace — a
leading space survives
.lower()unchanged. - Cross-reference:
strip-whitespace(this chapter) — the two are typically chained as the opening cleaning steps. - Cross-reference:
normalize-text-fields(python-data-basics) for the pure-Python pattern that combines strip and lowercase in one pass.