Sub topic 2
Missing Values, Decimal Formats, Dates, and Excel Files
This chapter assumes basic Python, pandas, and DataFrame knowledge. You should also know how CSV and spreadsheet files store tabular data.
Missing Values and Decimal Formats
CSV files often use markers such as NA, N/A, -, or an empty field for missing data. Pandas converts many common markers to NaN, its missing-value marker. Use na_values for values specific to your source file.
The decimal argument defines the character used for the decimal point. European files often use a comma for decimals and a semicolon as the field separator.
import pandas as pd
from io import StringIO
text = """id;price;status
1;3,50;paid
2;N/A;pending
"""
df = pd.read_csv(
StringIO(text),
sep=";",
decimal=",",
na_values=["N/A"],
)
print(df)
print(df.dtypes)Here, price becomes a floating-point column, and the N/A value becomes missing. Check missing values before calculations:
print(df.isna().sum())Parsing Dates
Date columns may load as strings unless you ask pandas to parse them. Use parse_dates and provide date_format when the format is known.
text = """id;date
1;05/01/2024
2;11/02/2024
"""
df = pd.read_csv(
StringIO(text),
sep=";",
parse_dates=["date"],
date_format="%d/%m/%Y",
)
print(df.dtypes)
print(df["date"].dt.month.tolist())The format code %d/%m/%Y means day, month, and four-digit year. Verify the result because swapping day and month can produce valid but incorrect dates.
Reading an Excel File
Use read_excel for .xlsx workbooks. Select a sheet with sheet_name, or load every sheet with sheet_name=None.
import pandas as pd
summary = pd.read_excel(
"report.xlsx",
sheet_name="Summary",
skiprows=2,
usecols="A:C",
nrows=10,
)
sheets = pd.read_excel("report.xlsx", sheet_name=None)
for name, frame in sheets.items():
print(name, frame.shape)For .xlsx files, pandas commonly uses the openpyxl engine. Install it if your environment does not already include it:
# Run in a terminal:
# python -m pip install pandas openpyxlExercise
Which arguments load a semicolon-separated CSV with comma decimals and N/A as missing?
Show answer
Use sep=";", decimal=",", and na_values=["N/A"].