Sub topic 2
Saving a DataFrame to CSV
This chapter covers DataFrame.to_csv, the most common way to save pandas results. It assumes you can create and inspect a DataFrame, run Python scripts or notebooks, and recognize the dtypes int, float, string, and datetime. Only pandas is required. No extra libraries are needed for CSV.
What a CSV file is
CSV stands for comma-separated values. It is a plain text file. Each line is one row, and a separator character splits the values in that row. Almost every tool can open one: spreadsheets, databases, scripts in other languages, and text editors. That reach is why CSV is the default choice when you share data.
CSV stores no type information. Every value is text. A reader has to guess whether 2026-01-05 is a date or a string. A later chapter covers what this costs you. For now, keep in mind that the file holds text and nothing else.
Writing your first file
Start with a small DataFrame that has text, missing values, floats, and dates.
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)The call writes orders.csv in the current working directory. The file looks like this:
order_id,customer,amount,ordered_at
1,Ana,19.99,2026-01-05
2,Ben,5.5,2026-01-06
3,,,2026-01-07Three details are worth noticing:
- The header row holds the column names.
- Missing values (
NoneandNaN) become empty fields. Row 3 shows this in bothcustomerandamount. - The datetime column is written in ISO format (
YYYY-MM-DD). pandas leaves out the time part when every value is at midnight.
Why `index=False`
By default, to_csv also writes the DataFrame's index as the first column. For a default index (0, 1, 2, ...), that column has no meaning. It also causes a common bug. When you read the file back, the old index appears as an extra column named Unnamed: 0.
Pass index=False unless the index carries real information, such as dates or IDs. If it does, give the index a name first so the column has a useful header:
df.set_index("order_id").to_csv("orders_indexed.csv")Here order_id is the index and is written as the first column under its own name.
Where the file goes
The first argument is a path. It can be relative to the working directory or absolute. If the target folder does not exist, pandas raises an error. It does not create folders. You can create the folder first with pathlib:
from pathlib import Path
out_dir = Path("exports")
out_dir.mkdir(exist_ok=True)
df.to_csv(out_dir / "orders.csv", index=False)An existing file with the same name is overwritten without warning. Check the path before you run a script that writes to a location you care about.
If you leave out the path, to_csv returns the CSV text as a string. This helps when you want to inspect the output without creating a file:
print(df.to_csv(index=False))Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Extra `Unnamed: 0` column after reading | The index was written | Use `index=False` |
| `OSError` or `FileNotFoundError` on write | The folder does not exist | Create it with `mkdir` |
| `PermissionError` on Windows | The file is open in Excel | Close it and rerun |
| Old data appears in the file | A previous run wrote to the same path | Use a new name or check the path |
How the write flows
Exercise
You save a DataFrame with df.to_csv("data.csv"). After pd.read_csv("data.csv"), the result has an extra column named Unnamed: 0. Why does this happen, and how do you prevent it?
Show answer
to_csv writes the index as the first column by default, and read_csv reads it back as an ordinary unnamed column. Prevent it by saving with df.to_csv("data.csv", index=False).