Sub topic 1
Which format should you save to?
Prerequisites
You should know basic Python, how to create and inspect a pandas DataFrame, and how to run a script or notebook. You should also recognize common dtypes such as integers, floats, strings, and datetimes.
Which format should you save to?
Choose the format based on who will use the file and whether pandas must preserve dtypes.
| Format | Best for | Main trade-off |
|---|---|---|
| CSV | Simple data exchange and text-based tools | Loses dtype information |
| Excel | People who work in spreadsheets | Requires an Excel engine and has size limits |
| Parquet | Analytics and pandas-to-pandas storage | Needs a Parquet engine and is less human-readable |
CSV stores values as text separated by delimiters. Excel stores one or more tables in a workbook. Parquet is a columnar format that stores values with metadata about their dtypes.
Saving a DataFrame to CSV
Use DataFrame.to_csv() to write a CSV file:
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3],
"customer": ["Ana", "Ben", None],
"amount": [19.99, 5.5, None],
"ordered_at": pd.to_datetime(["2026-01-05", "2026-01-06", "2026-01-07"]),
})
df.to_csv("orders.csv", index=False)index=False prevents pandas from adding the DataFrame index as an extra column. The default output includes a header row and uses commas between fields.
Controlling the CSV output
Important options control how other programs interpret the file:
header=Falseomits column names.sep=";"uses semicolons instead of commas.na_rep="NA"writesNAfor missing values.float_format="%.2f"writes two digits after the decimal point.date_format="%Y-%m-%d"controls datetime text.encoding="utf-8"selects the character encoding.
df.to_csv(
"orders_eu.csv",
index=False,
sep=";",
decimal=",",
na_rep="NA",
float_format="%.2f",
date_format="%Y-%m-%d",
encoding="utf-8",
)The decimal option is useful when a receiving application expects decimal commas.
Compressing CSV files and choosing an encoding
Pandas infers compression from a recognized extension such as .gz:
df.to_csv("orders.csv.gz", index=False, encoding="utf-8")UTF-8 supports most languages and is usually the safest default. Some older spreadsheet applications expect an encoding such as utf-8-sig; use it only when the receiving application requires a byte-order mark.
Exercise
Why should you usually pass index=False when exporting a DataFrame to CSV?
Show answer
It prevents the pandas index from becoming an unintended extra column.