Sub topic 3
Controlling the CSV output
The previous chapter wrote a DataFrame to CSV with the default settings. This chapter covers the options of to_csv that decide what ends up in the file: the index, the header, the separator, missing values, and number and date formatting. It assumes you can create a DataFrame, know the basic dtypes (int, float, string, datetime), and have pandas installed.
The working model
to_csv converts every cell to text, joins the cells of a row with a separator, and writes one row per line. Each option changes one step of that process. Nothing in the file records dtypes, so every choice you make here is a choice about text.
The examples below use this DataFrame. Calling to_csv() without a path returns the CSV text as a string, which lets you see the result without creating files.
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"]),
})
print(df.to_csv()),order_id,customer,amount,ordered_at
0,1,Ana,19.99,2026-01-05
1,2,Ben,5.5,2026-01-06
2,3,,,2026-01-07The first column is the index, the header has an empty name for it, and both missing values became empty fields.
The index
By default to_csv writes the index as the first column. For a default RangeIndex (0, 1, 2, ...) this column carries no information. When you read the file back, pandas has no way to know it was an index, so it becomes a column named Unnamed: 0. This is one of the most common CSV bugs in real projects.
Pass index=False to drop it:
print(df.to_csv(index=False))order_id,customer,amount,ordered_at
1,Ana,19.99,2026-01-05
2,Ben,5.5,2026-01-06
3,,,2026-01-07Keep the index when it holds data, such as the result of a groupby. Give it a name so the header cell is not empty:
totals = df.groupby("customer")["amount"].sum()
print(totals.to_csv(index_label="customer"))index_label sets the header text for the index column. If the index already has a name, as customer does here, that name is used automatically. A MultiIndex writes one column per level, and index_label then takes a list.
Header and column selection
header=False omits the header row, which is useful when appending to an existing file or when the consumer expects data only. Passing a list of strings renames the columns in the output without changing the DataFrame:
print(df.to_csv(index=False, header=["id", "name", "total", "date"]))The list must have exactly as many names as written columns, or pandas raises a ValueError.
columns selects and orders the columns to write:
print(df.to_csv(index=False, columns=["ordered_at", "order_id"]))Selecting columns here is equivalent to df[["ordered_at", "order_id"]].to_csv(...). Use whichever reads better. The explicit columns argument makes the output schema visible in the call.
Separator, decimal mark, and quoting
sep sets the field separator and must be a single character. In many European locales the decimal mark is a comma, so spreadsheet programs there expect ; as the separator and , as the decimal mark. The decimal argument controls the mark that to_csv writes for floats.
print(df.to_csv(index=False, sep=";", decimal=","))order_id;customer;amount;ordered_at
1;Ana;19,99;2026-01-05
2;Ben;5,5;2026-01-06
3;;;2026-01-07If you set decimal="," but leave sep=",", every float contains the separator. pandas then wraps those fields in quotes ("19,99") to keep the file parseable. The file is valid, but many tools handle it badly. Change both options together.
Quoting follows quoting, which defaults to csv.QUOTE_MINIMAL: a field is quoted only if it contains the separator, the quote character, or a line break. Embedded quote characters are doubled. Other modes come from the standard csv module:
import csv
people = pd.DataFrame({"name": ['Lee, Kim', 'Say "hi"'], "age": [31, 42]})
print(people.to_csv(index=False))
print(people.to_csv(index=False, quoting=csv.QUOTE_NONNUMERIC))name,age
"Lee, Kim",31
"Say ""hi""",42
"name","age"
"Lee, Kim",31
"Say ""hi""",42QUOTE_NONNUMERIC quotes all non-numeric fields and the header. QUOTE_ALL quotes everything. You rarely need either, but some importers insist on one of them.
Missing values
Without na_rep, None, NaN, and NaT all become an empty field. Set na_rep to write an explicit marker:
print(df.to_csv(index=False, na_rep="NA"))Three details matter here.
- An empty string and a missing value are both written as an empty field when
na_repis not set. After a round trip they cannot be told apart, and both come back asNaN. na_repapplies to every column, including dates and numbers. You cannot choose a different marker per column in one call. If you need that, convert the columns to strings first.- When you read the file back,
read_csvalready treatsNA,NaN,null, and a few other spellings as missing. A custom marker such as"missing"must be passed toread_csv(..., na_values=["missing"]), or it stays as text.
Number formatting
float_format controls how floats are rendered. It accepts a format string or a callable:
print(df.to_csv(index=False, float_format="%.2f"))
print(df.to_csv(index=False, float_format=lambda x: f"{x:.1f}"))The first call writes 19.99, 5.50, and an empty field. The second writes 20.0 and 5.5.
Keep these limits in mind:
float_formatrounds the stored value permanently. The file contains19.99, never the original binary float. Do not use it for data you will reload for further calculation unless the rounding is intended.- It applies to float columns only. Integer columns are written as they are.
- It applies to every float column in the frame. If one column needs six decimals and another needs two, round them separately first with
df.round({"amount": 2, "rate": 6}), then write withoutfloat_format. - When
float_formatanddecimalare both set, the number is formatted first and the decimal mark is replaced afterwards.
Date formatting
For datetime columns, date_format takes a strftime pattern:
print(df.to_csv(index=False, date_format="%d/%m/%Y"))Without date_format, pandas writes ISO 8601 text. A column whose values are all at midnight is written as 2026-01-05. A column with a time component is written as 2026-01-05 13:45:00, with fractional seconds if they are present. ISO format is the safest default because it sorts correctly as text and parses unambiguously. Formats like %d/%m/%Y are easy to misread: 03/04/2026 is March 4th in the US and April 3rd in most of Europe. Use them only when a consumer requires them.
date_format applies to datetime columns and a datetime index. It does not touch columns that already hold strings.
A complete European-style export
This is the call from the options above, combined. It writes a file that a spreadsheet in a German or French locale opens with the columns split correctly:
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 file contains:
order_id;customer;amount;ordered_at
1;Ana;19,99;2026-01-05
2;Ben;5,50;2026-01-06
3;NA;NA;2026-01-07To read it back with the same meaning, mirror the options: pd.read_csv("orders_eu.csv", sep=";", decimal=",", parse_dates=["ordered_at"]). The next chapters cover encoding and what a round trip loses.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Extra `Unnamed: 0` column after reading | Index was written | Use `index=False`, or read with `index_col=0` |
| Numbers like `"19,99"` in quotes | `decimal=","` with `sep=","` | Use `sep=";"` |
| `ValueError: Writing N cols but got M aliases` | `header` list has the wrong length | Match the number of written columns |
| Values rounded in reloaded data | `float_format` used on data you still need | Round only for presentation files |
| Custom marker read back as text | `na_rep` not matched in `read_csv` | Pass `na_values` when reading |
| Dates misread after export | Ambiguous `date_format` | Use ISO `%Y-%m-%d` |
Exercise
A colleague in Germany needs a file with columns id and price from a DataFrame df whose columns are named order_id and amount. Prices must use a comma as the decimal mark and show exactly two decimals, the fields must be separated by semicolons, and no index column may appear. Write the to_csv call that creates prices.csv.
Show answer
df.tocsv("prices.csv", index=False, sep=";", decimal=",", floatformat="%.2f", columns=["order_id", "amount"], header=["id", "price"]). The columns argument picks the two columns in order, and header renames them in the output only. Using sep=";" together with decimal="," avoids quoting the prices.
Exercise
You write a DataFrame with df.to_csv("out.csv") and later read it with pd.read_csv("out.csv"). The result has an unexpected first column. What is it called, why does it exist, and what are two ways to avoid it?
Show answer
It is called "Unnamed: 0". It is the index, which tocsv wrote as a column with an empty header. Avoid it by writing with index=False, or by reading with indexcol=0 to turn that column back into the index.