Sub topic 6
Missing values and decimal formats
This chapter assumes you can run Python scripts or notebooks, have pandas installed, and know what a DataFrame is. You should also have used read_csv with its default settings. Here you will control which text becomes a missing value and how numbers written in non-US formats are read. Both are decided at load time, and mistakes made here usually do not raise an error. They show up later as wrong totals or text columns that should be numeric.
How pandas decides what is missing
A missing value in pandas is a cell that holds no usable data. read_csv converts certain strings to NaN, which stands for "not a number". It is the standard missing marker for floating-point data.
By default, these strings are treated as missing:
- An empty field
NA,N/A,NaN,nan,NULL,null#N/A,#NA,-NaN,-nan,<NA>,n/a,1.#IND,1.#QNAN,#N/A N/A
You can see this with a small file.
import pandas as pd
from io import StringIO
text = "id,score,comment\n1,10,ok\n2,,NA\n3,n/a,null\n"
df = pd.read_csv(StringIO(text))
print(df)
print(df.isna())Both score and comment contain NaN in rows 2 and 3. The score column is read as float64, because NaN is a float and a column that holds it cannot stay int64 in the default NumPy-backed types.
Adding your own markers
Real files often use their own placeholders, such as -, missing, ? or -999. The na_values argument adds strings to the default list.
import pandas as pd
from io import StringIO
text = "id,temp\n1,21.5\n2,-999\n3,?\n4,19.0\n"
df = pd.read_csv(StringIO(text), na_values=["-999", "?"])
print(df)
print(df["temp"].dtype)Without na_values, the ? would keep the whole temp column as text, because one non-numeric entry is enough to prevent numeric parsing. With it, temp loads as float64.
Note that the markers are strings. Pass "-999", although a number such as -999 also works for numeric columns.
Different markers per column
If -1 means missing in one column but is a valid value in another, pass a dictionary. The keys are column names.
import pandas as pd
from io import StringIO
text = "id,age,balance\n1,34,-1\n2,-1,250\n"
df = pd.read_csv(StringIO(text), na_values={"age": [-1]})
print(df)Here -1 is missing in age but stays a real number in balance.
Replacing the defaults
By default, na_values is added to the built-in list. Two arguments change that behavior:
keep_default_na=Falseturns off the built-in list, so only strings you give inna_valuescount as missing.na_filter=Falseturns off missing-value detection completely. Everything is kept as it appears in the file. This can also speed up reading of large files that you know have no missing data.
import pandas as pd
from io import StringIO
text = "code,region\nA1,NA\nB2,EU\n"
default = pd.read_csv(StringIO(text))
literal = pd.read_csv(StringIO(text), keep_default_na=False)
print(default["region"].tolist())
print(literal["region"].tolist())The first list contains nan in place of "NA". The second keeps the string 'NA'. If you use keep_default_na=False and still want empty fields to be missing, add "" to na_values.
The following table summarizes how the three arguments combine.
| `keep_default_na` | `na_values` | Result |
|---|---|---|
| `True` (default) | not given | Only the built-in list is missing |
| `True` | given | Built-in list plus your values |
| `False` | given | Only your values |
| `False` | not given | Nothing is missing |
Decimal and thousands formats
Many countries write 3,50 for three and a half, and 1.234,56 for one thousand two hundred and thirty-four and fifty-six hundredths. If you read such text with defaults, pandas does not recognize the numbers. The column stays as object, which means Python strings.
Two arguments describe the format:
decimalis the character that separates the whole part from the fraction. The default is..thousandsis the character that groups digits. The default is none.
import pandas as pd
from io import StringIO
text = "item;price\nbook;1.234,56\npen;3,50\n"
df = pd.read_csv(StringIO(text), sep=";", decimal=",", thousands=".")
print(df)
print(df["price"].dtype)The price column is read as float64, with values 1234.56 and 3.5.
The file uses ; as its separator because a comma would clash with the decimal comma. That is why European CSV files so often use semicolons. If you set decimal="," and leave sep at its default, the comma is still treated as a field separator and the rows will split in the wrong places.
Combining both ideas
The two features work together. A file can use a decimal comma and its own missing marker at the same time. This is the example from the chapter plan, with the date handled in a later chapter.
import pandas as pd
from io import StringIO
text = "id;price;date\n1;3,50;05/01/2024\n2;N/A;11/02/2024\n"
df = pd.read_csv(
StringIO(text),
sep=";",
decimal=",",
na_values=["N/A"],
parse_dates=["date"],
date_format="%d/%m/%Y",
index_col="id",
)
print(df.dtypes)price becomes float64 with one NaN, and date becomes datetime64[ns]. Here N/A is already in the default list, so na_values is redundant for it. It is shown to make the intent visible, which is a reasonable habit when a file's placeholders matter to your analysis.
Missing values and data types
A missing value affects the type that a column can have.
| Column content | Default dtype |
|---|---|
| Whole numbers, no missing | `int64` |
| Whole numbers with a missing value | `float64` |
| Text with a missing value | `object` (missing shown as `NaN`) |
| True/False with a missing value | `object` |
If you need integers that allow missing values, ask for a nullable type with the dtype argument. The capitalized Int64 supports a missing marker called pd.NA.
import pandas as pd
from io import StringIO
text = "id,count\n1,5\n2,\n3,7\n"
plain = pd.read_csv(StringIO(text))
nullable = pd.read_csv(StringIO(text), dtype={"count": "Int64"})
print(plain["count"].dtype)
print(nullable["count"].dtype)
print(nullable)The first dtype is float64 and the second is Int64. With Int64, the values print as 5, <NA>, 7, with no decimal points.
Common errors
These are the problems you are most likely to meet.
- A numeric column loads as
object. At least one cell holds text that pandas does not treat as missing, for example-,?orn.a.. Find it withdf[~df["col"].str.match(r"^-?\d+(\.\d+)?$", na=True)], then add the marker tona_values. - Numbers like
3,50stay as strings. You forgotdecimal=",", or the file also needsthousands. - Rows have too many fields. You set
decimal=","but the file is comma separated. Quote the decimal values in the source, or fix the file's separator. - A real value vanished. A code such as
NAwas read as missing. Usekeep_default_na=False. - Integers became floats. A missing value forced
float64. UseInt64if you need integers.
Checking the result
After loading, confirm that the choices had the effect you wanted. Count missing values per column and confirm the numeric columns are numeric.
import pandas as pd
from io import StringIO
text = "id;price\n1;3,50\n2;?\n3;1.200,00\n"
df = pd.read_csv(
StringIO(text), sep=";", decimal=",", thousands=".", na_values=["?"]
)
print(df.isna().sum())
print(df.dtypes)The output shows one missing value in price and a float64 dtype. If price came out as object, there is still an unrecognized marker in the data. A fuller validation workflow comes in the last chapter of this tutorial.
Exercise
A file sales.csv is semicolon separated. Prices look like 1.299,90. The text unknown and the number 0 in the price column both mean the price is missing. Write the read_csv call that loads it with price as float64 and with these markers treated as missing only in price.
Show answer
Use a per-column na_values dictionary together with sep, decimal and thousands:
pd.readcsv("sales.csv", sep=";", decimal=",", thousands=".", navalues={"price": ["unknown", 0]})
The dictionary limits the extra markers to price, so a legitimate 0 in other columns is kept. The result has dtype float64 for price.
Exercise
A column region contains the code NA meaning North America. After read_csv with defaults, those rows show NaN. How do you keep them as text, and what must you add if empty fields should still be missing?
Show answer
Pass keep_default_na=False to stop NA from being converted. Then add na_values=[""] so that empty fields are still treated as missing.