Sub topic 9
Turning yes/no columns into booleans
This chapter assumes you can load a CSV into a DataFrame, select columns, and call str methods on a text column. You should also know that a pandas column with the dtype object holds arbitrary Python objects, usually strings. Earlier chapters covered astype, string cleaning and nullable dtypes. Here they are combined to solve one common problem: survey and export files often store flags as yes, no, Y, N, TRUE, 0 or an empty cell.
The goal is a column with the nullable boolean dtype. It has exactly three possible values: True, False and <NA>. Filters and counts then behave predictably, and a missing answer stays missing instead of being turned into a wrong answer.
Why astype(bool) is the wrong tool
astype(bool) does not read the text. It asks Python whether each object is truthy. Every non-empty string is truthy, including "no" and "false".
import pandas as pd
s = pd.Series(["yes", "no", "", "false"])
print(s.astype(bool).tolist())The output is [True, True, False, True]. The answer "no" became True, and only the empty string became False. No error is raised, so this bug passes silently into later calculations.
The recipe: normalize, map, convert
A reliable conversion has three steps, and each step has one job.
- Normalize the text with
str.strip()andstr.lower()so that" Yes","YES"and"yes"become one spelling. - Map each known spelling to
TrueorFalsewith a dictionary. Anything not in the dictionary becomesNaN. - Convert the result to the
booleandtype withastype("boolean").
import pandas as pd
raw = pd.Series([" Yes", "NO", "y", "N", None, "maybe"])
mapping = {
"yes": True, "y": True, "true": True, "1": True,
"no": False, "n": False, "false": False, "0": False,
}
clean = raw.str.strip().str.lower()
flags = clean.map(mapping).astype("boolean")
print(flags.dtype)
print(flags.tolist())The dtype prints as boolean, and the list is [True, False, True, False, <NA>, <NA>]. The missing value and the unrecognized answer "maybe" both end up as <NA>.
Why the dictionary should be explicit
A dictionary lists exactly which spellings you accept. This makes the conversion auditable: a reviewer can read the mapping and see what each answer means. It also makes unexpected values visible. The next section shows how to find them.
The alternative is Series.replace. It leaves unmatched values unchanged, so you get a column that mixes booleans with strings such as "maybe". That column is still object, and it hides the problem. Prefer map for this task.
Finding the values the mapping missed
After map, a missing cell and an unrecognized answer look the same: both are NaN. To tell them apart, compare against the original column, as you did in the chapter on finding failed conversions.
mapped = clean.map(mapping)
unmapped = raw[mapped.isna() & raw.notna()]
print(unmapped.tolist())This prints ['maybe']. Rows that were already missing in raw are excluded by raw.notna(), so only real surprises remain.
Before you write the mapping, it helps to see which spellings exist. Count the normalized values, including missing ones:
print(clean.value_counts(dropna=False))Read this table first, then build your dictionary from what you see. If the unmapped list contains a spelling you can interpret, such as "yeah", add it to the dictionary. If you cannot interpret it, leave it as <NA> and report it to whoever owns the data.
Why the nullable boolean dtype
NumPy's bool dtype has no way to represent a missing value. If a column has even one missing entry, it cannot be plain bool. The practical options are:
| Representation | dtype | Can hold missing? | What happens with a gap |
|---|---|---|---|
| Plain NumPy booleans | `bool` | No | Conversion forces a choice, often a wrong one |
| Booleans and NaN together | `object` | Yes | Works, but slow, and `sum` and comparisons are unreliable |
| Nullable booleans | `boolean` | Yes | The gap stays `<NA>` and the dtype is unchanged |
Use bool only when you are certain every row has an answer. Even then, boolean is safe, and a column with no gaps behaves the same way.
Working with <NA> afterwards
Counting and averaging skip <NA>, which is usually what you want:
flags = pd.Series([True, False, True, None], dtype="boolean")
print(flags.sum())
print(flags.mean())
print(flags.isna().sum())The sum is 2. The mean is about 0.667, because it divides by the 3 answered rows, not by 4. The count of missing values is 1.
Logical operators follow three-valued logic. True | <NA> is True, because the result cannot depend on the unknown value. False | <NA> is <NA>. This is more careful than treating a gap as False.
When you filter, a nullable boolean mask treats <NA> as False. To make that decision visible in your code, write it out:
df = pd.DataFrame({"id": [1, 2, 3, 4], "active": flags})
print(df[df["active"].fillna(False)]["id"].tolist())This prints [1, 3]. Use fillna(False) only where the question is "which rows are definitely yes", and keep the original column unchanged.
Converting several columns at once
Wrap the recipe in a function so that every flag column is converted the same way. This also keeps the mapping in one place.
import pandas as pd
MAPPING = {
"yes": True, "y": True, "true": True, "t": True, "1": True,
"no": False, "n": False, "false": False, "f": False, "0": False,
}
def to_boolean(col: pd.Series) -> pd.Series:
cleaned = col.astype("string").str.strip().str.lower()
return cleaned.map(MAPPING).astype("boolean")
df = pd.DataFramesletter": ["Yes", "no", "Y", None],
"premium": ["N", "n", "TRUE", "false"],
})
flag_cols = ["newsletter", "premium"]
df[flag_cols] = df[flag_colsean)
print(df.dtypes)Both columns now show the dtype boolean. The call astype("string") ature the str methods work even if a column contains non-string objects such as numbers.
Columns that are already 0 and 1
If a column holds the integers 0 and 1, there is no text to clean. A direct conversion works:
s = pd.Series([1, 0, 1, 1])
print(s.astype("boolean").tolist())The result is [True, False, True, True]. Check first that the column contains only 0, 1 and missing values. A column that also contains 2 or -1 has a different meaning, and you should look at it before converting.
Converting while reading the CSV
pd.read_csv can recognize extra spellings of true and false at load time with the true_values and false_values arguments. If a column consists only of those spellings, it arrives as bool.
import io
import pandas as pd
csv = "id,active\n1,yes\n2,no\n3,yes\n"
df = pd.read_csv(
io.StringIO(csv),
true_values=["yes"],
false_values=["no"],
)
print(df["active"].dtype)This prints bool. The match is exact and case-sensitive, so Yes would not be recognized by true_values=["yes"]. When a column has empty cells, the result may arrive as object, mixing booleans with NaN. Finish the job with astype("boolean") after loading:
csv = "id,active\n1,yes\n2,\n3,no\n"
df = pd.read_csv(
io.StringIO(csv),
true_values=["yes"],
false_values=["no"],
)
df["active"] = df["active"].astype("boolean")
print(df["active"].tolist())The list is [True, <NA>, False]. If the source uses many spellings or inconsistent case, load the column as text and use the normalize, map and convert recipe instead. It gives you the validation step that true_values does not.
Common mistakes
- Using
astype(bool)on text. Every non-empty string becomesTrue. - Forgetting to normalize case and whitespace, so
"Yes "silently maps toNaN. - Skipping the check for unmapped values, which hides typos and new spellings.
- Assigning
Falseto missing answers just to get a plainboolcolumn. This changes "unknown" into "no" and biases every later count. - Mapping to the strings
"True"and"False"instead of the Python valuesTrueandFalse.
Exercise
A column answered contains the values "Yes", " no", "NO", "unsure" and a missing cell. Write the code that produces a nullable boolean column and a list of the answers that were not recognized and not missing.
Show answer
Normalize, map, convert, then compare with the original: mapping = {"yes": True, "no": False} clean = answered.str.strip().str.lower() mapped = clean.map(mapping) flags = mapped.astype("boolean") unrecognized = answered[mapped.isna() & answered.notna()].tolist() The flags column is [True, False, False, <NA>, <NA>] and unrecognized is ["unsure"]. The missing cell is excluded by answered.notna().
Exercise
Why does pd.Series(["no", "no", "no"]).astype(bool) return all True, and what is the correct conversion?
Show answer
astype(bool) tests truthiness, and every non-empty string is truthy, so "no" becomes True. The correct conversion maps the text with a dictionary and then casts: pd.Series(["no", "no", "no"]).map({"no": False}).astype("boolean") gives three False values.