Types and Parsing
Parse Boolean Labels
Convert human-readable yes/no strings in varied case to Python booleans.
By hand, normalise each string to lowercase and look it up in a mapping
dict. With pandas, .str.lower() lowercases the column in one pass, then
.map(dict) remaps each element to its boolean value.
By hand
Define a mapping dict covering all accepted forms ('yes', 'y',
'no', 'n'). For each label, call s.lower() before the lookup so
mixed-case inputs match. The trace shows result accumulating booleans.
naive.py
mapping = {'yes': True, 'y': True, 'no': False, 'n': False}
labels = ['yes', 'no', 'Y', 'N', 'yes']
result = []
for s in labels:
result.append(mapping[s.lower()])
print('RESULT:', result)
With pandas
.str.lower() lowercases the entire string column, then .map(dict)
replaces each value with the corresponding boolean. The dtype of the
resulting Series is bool because every input maps to a value.
library.py
import pandas as pd
from dalib.display import set_display
set_display()
labels = ['yes', 'no', 'Y', 'N', 'yes']
df = pd.DataFrame({'x': labels})
s = df['x'].str.lower().map({'yes': True, 'y': True, 'no': False, 'n': 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: bool
values: [True, False, True, False, True]
RESULT: [True, False, True, False, True]
Implementation notes
- When all inputs are in the mapping, the result Series has dtype
bool. If any string is unmapped,.mapreturnsNaNfor that position and the dtype becomesobject— useerrors='raise'or validate inputs upstream to catch surprises. - The normalization dict can be extended for common variants:
'true','false','1','0','on','off'. - Cross-reference:
coerce-bad-numbers(this chapter) for the analogous pattern of mapping strings to numerics where some values may be invalid.