Data Analyst Interview
Menu
Browse in your language. All mock interviews, preparation sessions and feedback are in English only.

Pandas astype(bool): Why the String “False” Becomes True

Python • CSV data quality

Why Does pandas Convert the String “False” to True?

Parse exported flags with an explicit mapping, preserve unknown values, and check the denominator before reporting a conversion rate.

By Prakhar Shrivastava · October 9, 2026

Answer: astype(bool) evaluates truthiness; it does not interpret the meaning of text. A nonempty string such as "False" or "0" is truthy. Normalize the text, map the values your source contract permits, and use pandas’ nullable "boolean" dtype so missing or unrecognized input does not silently become a confirmed outcome.

What goes wrong in a CSV export?

Suppose a sales-operations export contains six fictional lead records from the US, UK, and Germany. Its confirmed flag accepts true, false, 1, and 0, ignoring case and surrounding whitespace. Blank fields mean the status is unavailable. These assumptions describe this example; check your own export specification before applying the mapping.

import pandas as pd

print(pd.Series(["True", "False", "0"]).astype(bool).tolist())
# [True, True, True]

All three strings contain characters, so all three become true. The result is valid Python behavior but the wrong business interpretation. This can inflate a count even when the transformation completes without an exception. Empty strings behave differently, and missing-value representations can vary; a truthiness cast is not a validation strategy.

How do you parse the flags without losing the raw values?

df = pd.DataFrame({
    "lead_id": ["US1", "US2", "UK1", "UK2", "DE1", "DE2"],
    "confirmed_raw": ["True", "False", " true ", "0", "", None],
})

normalized = (
    df["confirmed_raw"].astype("string")
    .str.strip().str.lower()
)
mapping = {"true": True, "false": False, "1": True, "0": False}
df["confirmed"] = normalized.map(mapping).astype("boolean")

missing = normalized.isna() | normalized.eq("").fillna(False)
unexpected = (~missing) & (~normalized.isin(mapping))
print(df[["lead_id", "confirmed"]])
  lead_id  confirmed
0     US1       True
1     US2      False
2     UK1       True
3     UK2      False
4     DE1       <NA>
5     DE2       <NA>

The lowercase "boolean" extension dtype can hold true, false, and a missing value. The explicit "string" conversion supports string operations while retaining missingness. Keep confirmed_raw for investigation: replacing the source field would make it harder to explain which input caused a problem.

How do missing and unexpected values differ?

Both can produce a missing parsed flag, but they need different follow-up. A blank or null is unavailable information. A value such as "yes" is unexpected under this contract. It may be a legitimate source-system change, a manual entry, or an error. Do not add it to the true mapping just because it looks plausible.

print("Missing:", int(missing.sum()))       # 2
print("Unexpected:", int(unexpected.sum())) # 0
review = df.loc[unexpected, ["lead_id", "confirmed_raw"]]

assert df["confirmed"].iloc[:4].tolist() == [True, False, True, False]
assert df["confirmed"].isna().sum() == 2

For an unexpected input, retain the record in an exception report and resolve the allowed vocabulary with the data owner. Avoid fillna(False) unless the business definition explicitly states that unavailable status means false. That shortcut turns uncertainty into an apparent negative outcome.

Which denominator should the report use?

This fixture has two confirmed records, two explicitly false records, and two unavailable statuses. The confirmed share of all six records is 33.33%. The confirmed share among the four records with known status is 50%. Neither number should be labeled simply “conversion rate” without its population definition.

confirmed_count = int(df["confirmed"].sum()) # 2
known_count = int(df["confirmed"].count())   # 4
all_count = len(df)                         # 6

all_share = confirmed_count / all_count if all_count else None
known_share = confirmed_count / known_count if known_count else None

Publish the unknown-status count alongside either share. A parsed export flag is only as trustworthy as its source definition; it does not by itself prove that a lead was confirmed by a server or CRM. For event collection, see the confirmed-lead tracking plan. For the same denominator issue in SQL, see conditional counts and unknown outcomes.

Checks before using this in a pipeline

Test accepted values, capitalization, whitespace, blanks, nulls, and at least one unexpected value. Preserve identifier text during ingestion using the CSV leading-zero guide. Audit numeric fields separately with invalid-value checks for to_numeric. This example’s six checks passed with pandas 2.2.3; rerun them in your deployed environment when upgrading.

Primary sources

Leave a Comment

✉ WhatsApp