In pandas read_csv, how do na_values and keep_default_na decide which strings become NaN, and when must you turn the defaults off?
answer
- a built-in list of markers
- appended, not replaced
- a country called Namibia
- a per-column dict
basics
~10 sread_csv treats a built-in list of strings ('', 'NA', 'NULL', 'null', 'None', 'nan' and others) as missing, and na_values adds to that list. Set keep_default_na=False when real values such as 'NA' must survive.
solid answer
~30 s`read_csv` starts from a default list of missing markers: the empty field, `NA`, `N/A`, `NULL`, `null`, `None`, `NaN`, `nan`, `#N/A` and a few more. `na_values` is **added** to that list, not substituted for it, so `na_values=['-']` still turns the country code `NA` (Namibia) into NaN. `keep_default_na=False` drops the defaults: with `na_values` given, only your markers count; without it, nothing is parsed as missing, not even blanks. A dict such as `na_values={'ms': ['-']}` sets markers per column, and with `keep_default_na=False` the columns you leave out get no markers at all. `na_filter=False` switches detection off entirely and ignores both arguments.
code
python · 16 linesimport io
import pandas as pd
raw = "country,ms\nNA,120\nDE,-\n,95\n"
default = pd.read_csv(io.StringIO(raw))
print(default["country"].isna().sum()) # 2: 'NA' and the blank
strict = pd.read_csv(
io.StringIO(raw),
keep_default_na=False,
na_values={"country": [""], "ms": ["", "-"]},
)
print(strict["country"].tolist()) # ['NA', 'DE', nan]
print(strict["ms"].tolist()) # [120.0, nan, 95.0]go deeper
Know that read_csv turns blanks and strings like NA and NULL into missing values without being asked, and that na_values adds more.
Walk through the four keep_default_na and na_values cases, the per-column dict, and what happens to blanks when the defaults are off.
Spot real values eaten by the default list in production data, fix the read with a per-column dict, and verify with isna counts.
Make missing-marker policy part of each external feed's contract, so readers do not depend on the default list matching the producer.
## The default missing markers Every `read_csv` call, unless told otherwise, checks each field against a **default list of missing-value markers**. The list in the parser source is: - the empty string `''` - `NA`, `<NA>`, `#NA`, `N/A`, `n/a`, `#N/A`, `#N/A N/A` - `NULL`, `null`, `None` - `NaN`, `-NaN`, `nan`, `-nan` - `1.#IND`, `-1.#IND`, `1.#QNAN`, `-1.#QNAN` A field matching any of them becomes a missing value (NaN in a float or text column). That is convenient for exports from spreadsheets and databases, and it is wrong whenever one of those strings is a real value: the ISO country code `NA` for Namibia, or `None` used as a literal category label. Matching is exact and case-sensitive, so `Null` survives while `null` and `NULL` do not. ## How the two arguments combine `na_values` adds markers; `keep_default_na` says whether the default list stays. The docstring spells out four cases: | `keep_default_na` | `na_values` given? | Markers used | |---|---|---| | `True` (default) | yes | defaults **plus** `na_values` | | `True` (default) | no | defaults only | | `False` | yes | `na_values` only | | `False` | no | none: no string is parsed as missing | The last row surprises people: with `keep_default_na=False` and nothing else, an empty field is no longer missing. In a text column it stays an empty string, and in a column of numbers a blank that is not a marker may keep the column from being parsed as numeric. So the usual strict call names the blank explicitly: ```python df = pd.read_csv(path, keep_default_na=False, na_values=["", "-"]) ``` Numbers work too: `na_values=[5]` treats both `5` and `5.0` as missing. ## Per-column markers with a dict A dict maps column names to their own markers, which is what a clickstream file with mixed conventions needs: `-` means missing in the latency column, while `NA` is a real country. - With `keep_default_na=True`, each listed column gets **its markers plus the defaults**, and every unlisted column gets the defaults. A dict alone therefore never protects `NA` in the country column. - With `keep_default_na=False`, each listed column gets **only its markers**, and unlisted columns get **none**. List every column whose blanks should be missing. ```python df = pd.read_csv( path, keep_default_na=False, na_values={"country": [""], "ms": ["", "-"]}, ) ``` ## Traps that show up in real files - **Placeholder strings in numeric columns.** A latency column that uses `-` or `?` for "no value" cannot be parsed as numbers unless that placeholder is a marker. Without it the whole column comes back as text instead of `float64`, and the first arithmetic on it fails far from the read. - **Literal words that look like markers.** Country code `NA`, a product called `None`, or a status value `null` are all read as missing by default. Nothing warns you; the values simply turn into NaN. - **Sentinel numbers.** Some exports write `-999` or `0` for unknown. `na_values=[-999]` catches both `-999` and `-999.0`, because numeric markers are matched in their float form as well. - **Per-file drift.** A feed that used blanks last month and `NULL` this month changes nothing under the defaults, but breaks a strict call that listed only `''`. Strict reads need the marker list kept in step with the producer. ## Switching detection off and engine limits 1. **`na_filter=False`** skips missing-value detection entirely; the docstring notes that `keep_default_na` and `na_values` are then ignored. It speeds up reading a large file that is known to contain no missing markers, and only then. 2. **The PyArrow engine is stricter.** With `engine='pyarrow'`, a dict for `na_values` raises `ValueError`, and every marker must be a string. 3. **Check after reading.** `df.isna().sum()` per column right after the read shows whether a marker you did not expect turned real values into missing ones. ## Choosing the call For files you control, the defaults are usually fine. For third-party exports, decide which strings mean missing in which column, write that down as a dict with `keep_default_na=False`, and keep identifier-like columns such as country codes out of the default list's reach.
- You pass na_values={'ms': ['-']} and leave keep_default_na alone. Is 'NA' in the country column safe?No. With `keep_default_na=True`, a column missing from the dict still uses the default markers, and `NA` is one of them, so Namibia becomes NaN. The dict only adds `-` to the latency column. To protect the country code, set `keep_default_na=False` and give the country column its own list, such as `['']`.
- When is na_filter=False the right call?When the file is known to contain no missing markers and read speed matters, for example a large machine-written extract with every field populated. It skips detection completely, so `na_values` and `keep_default_na` are ignored and blanks are not treated as missing. On a file that can contain blanks it silently changes the data instead of saving time.
- na_values replaces the default missing markers
- keep_default_na=False on its own still treats blank fields as missing
- A dict na_values limits the default markers to the listed columns
- na_filter=False keeps only empty fields as missing
- The string 'NA' is only missing when na_values lists it