Sub topic 6
Missing values and decimal formats
This chapter assumes you can run read_csv and read its arguments, as covered in the earlier chapters on loading CSV files and setting data types. Here you control which text becomes a missing value and how numbers written in other regional formats are read.
How pandas decides a cell is missing
While parsing, read_csv compares each cell's text with a set of markers. A match becomes NaN, which is pandas' missing-value marker. The default markers include an empty cell, NA, N/A, n/a, NaN, nan, NULL, null, None and #N/A.
The result affects the column's data type. If one cell holds unrecognised text such as -, pandas cannot build a numeric column. The whole column becomes object (strings), and sums and means fail or give wrong results.
Adding your own markers
The na_values argument adds markers to the defaults. The next example reads a file where - means "no price".
import pandas as pd
from io import StringIO
text = "id,price\n1,3.5\n2,-\n3,4.25\n"
df = pd.read_csv(StringIO(text), na_values=["-"])
print(df.dtypes)
print(df["price"].isna().sum())price loads as float64, with one missing value. Without na_values, it would load as object.
You can also limit a marker to one column by passing a dictionary, for example na_values={"price": ["-"]}. Other columns then keep - as ordinary text.
Turning off the default markers
Sometimes a default marker is real data. The country code for Namibia is NA. Set keep_default_na=False to stop pandas treating the defaults as missing, and list only the markers you want.
import pandas as pd
from io import StringIO
text = "code,country\nNA,Namibia\nUS,United States\n,Unknown\n"
df = pd.read_csv(StringIO(text), keep_default_na=False, na_values=[""])
print(df["code"].tolist())
print(df["code"].isna().sum())The list is ['NA', 'US', nan]. NA stays as text and only the empty cell is missing.
Decimal and thousands separators
Many countries write 3,50 for 3.5 and 1.200,75 for 1200.75. Two arguments handle this:
| Argument | Meaning | Default |
|---|---|---|
| `decimal` | Character that separates the fraction | `.` |
| `thousands` | Character that groups digits | none |
If a file uses a comma as the decimal character, it usually cannot also use a comma as the field separator. Such files normally use ;, so set sep too.
import pandas as pd
from io import StringIO
text = "id;price\n1;3,50\n2;-\n3;1.200,75\n"
df = pd.read_csv(
StringIO(text),
sep=";",
decimal=",",
thousands=".",
na_values=["-"],
)
print(df["price"].tolist())
print(df["price"].dtype)The prices are [3.5, nan, 1200.75] and the dtype is float64.
Common mistakes
- Setting
decimal=","but forgettingsep=";". Every row then splits into the wrong number of fields. - Setting
decimal=","on a column that also has.thousands separators, but omittingthousands=".". The value1.200,75stays as text. - Cleaning markers after loading with
.replace("-", np.nan). This works, but the column is alreadyobjectand needspd.to_numericafterwards. Passingna_valuesat load time avoids the extra step. - Assuming a column is clean because
read_csvraised no error. Always checkdf.dtypesanddf.isna().sum().
Exercise
A semicolon-separated file has a column amount with values like 2.500,00 and the text n.d. for unknown amounts. Which read_csv arguments make amount a float64 column with NaN for the unknown values?
Show answer
Use sep=";", decimal=",", thousands="." and na_values=["n.d."]. The separator settings turn 2.500,00 into 2500.0. The marker list turns n.d. into NaN, so every remaining cell converts to a number and the column is float64.