Sub topic 9
Turning yes/no columns into booleans
This chapter assumes you can build a pandas Series, use the .str accessor, and read a column's dtype. Survey and export files often store answers like "yes" and "no" as text. Text answers can't be used directly as filters or counted with sum(). A boolean column fixes that.
Why a boolean column is worth having
A text column stores each answer as a Python string in an object column. A boolean column stores true or false values. That gives you three benefits:
- You can filter with
df[df["active"]]instead of comparing strings. df["active"].sum()counts the true values, andmean()gives their share.- The column states that only two answers are valid.
Why astype(bool) is the wrong tool
It is tempting to call astype(bool) on a text column. That converts by truthiness, not by meaning. Every non-empty string counts as true, including "no".
import pandas as pd
s = pd.Series(["yes", "no"])
print(s.astype(bool).tolist())The output is [True, True]. The "no" became True. Use an explicit mapping instead.
Mapping with a dictionary
Series.map with a dictionary replaces each value by looking it up. Any value that is not a key in the dictionary becomes missing. This is useful because unexpected answers do not turn into a guess.
import pandas as pd
s = pd.Series(["yes", "no", "yes", None])
flags = s.map({"yes": True, "no": False}).astype("boolean")
print(flags)After map, the column is still object and holds True, False and NaN. The final astype("boolean") converts it to the nullable boolean dtype. That dtype keeps the missing entry as <NA> and stays a true boolean column. The lowercase NumPy bool dtype cannot hold missing values.
Cleaning first, then mapping
Real data is rarely this tidy. You may see " Yes", "NO", or "y" in the same column. Normalize the text first with str.strip() and str.lower(), then map. Put every accepted spelling in the dictionary.
Afterward, check which values were not recognized. A value that was present in the raw data but is missing in the result did not match the mapping.
import pandas as pd
raw = pd.Series([" Yes", "NO", "y", "yes", None, "maybe"])
clean = raw.str.strip().str.lower()
mapping = {"yes": True, "y": True, "no": False, "n": False}
flags = clean.map(mapping).astype("boolean")
unmapped = raw[flags.isna() & raw.notna()]
print(flags)
print(unmapped)flags has four known answers and two <NA> entries. The unmapped Series shows only "maybe", because the None was already missing in the input. This is the same pattern you used to find failed numeric conversions. You can now decide whether "maybe" should be dropped, mapped, or investigated.
Common errors
- Using
astype(bool)on text. It marks every non-empty string as true. Usemap. - Skipping the cleaning step. "Yes" and "yes" are different keys, so "Yes" silently becomes missing.
- Forgetting the final
astype("boolean"). The mapped column staysobject, sosum()and filters may behave unexpectedly. - Not checking unmapped values. Unexpected answers become
<NA>without any warning.
Exercise
Exercise
A column subscribed contains "Y", "n", " YES", "No", and None. Write code that converts it to the nullable boolean dtype, and name one check you should run afterward.
Show answer
Normalize, map, convert, then check: clean = df["subscribed"].str.strip().str.lower() df["subscribed"] = clean.map({"y": True, "yes": True, "n": False, "no": False}).astype("boolean") Afterward, find unmapped values by comparing the raw column with the result, for example raw[df["subscribed"].isna() & raw.notna()], where raw is a copy of the original column made before the conversion. Any rows it returns held answers the mapping did not cover.