Use df.to_csv("filename.csv", index=False) to export a Pandas DataFrame to a CSV file while excluding Pandas’ default numeric row index (0, 1, 2...).
Basic Example
import pandas as pd
# 1. Create a sample DataFrame
df = pd.DataFrame({
"product": ["Laptop", "Mouse", "Keyboard"],
"price": [1200.50, 25.00, 75.99],
"in_stock": [True, True, False],
})
# 2. Export to a CSV file without writing the numeric row index
df.to_csv("inventory.csv", index=False, encoding="utf-8")
Output (inventory.csv):
product,price,in_stock
Laptop,1200.5,True
Mouse,25.0,True
Keyboard,75.99,False
Key Details & Common Options
- Omitting the row index (
index=False): By default,to_csv()writes the DataFrame’s index as an unnamed first column (Unnamed: 0when read back). Always passindex=Falseunless your index contains meaningful labels (such as timestamps or unique IDs). - Excel compatibility with UTF-8 BOM (
encoding="utf-8-sig"): Standard UTF-8 CSV files containing accented characters, currency symbols, or non-Latin scripts often render garbled text when opened directly in Microsoft Excel on Windows. Useencoding="utf-8-sig"to prepend a Byte Order Mark so Excel detects UTF-8 automatically. - Exporting a subset of columns (
columns=[...]): Pass a list of column names to export only specific fields in a custom order without slicing the DataFrame beforehand:df.to_csv("prices_only.csv", columns=["product", "price"], index=False) - Appending rows to an existing CSV (
mode="a",header=False): To append new records to an existing file without duplicating the column header row, combine append mode withheader=False:from pathlib import Path file_path = Path("inventory.csv") df.to_csv(file_path, mode="a", header=not file_path.exists(), index=False) - Writing compressed CSVs directly (
compression="infer"): Pandas automatically compresses the output based on the file extension (e.g.,df.to_csv("inventory.csv.gz", index=False)or.zip,.bz2,.zst).
Common to_csv() Parameters Reference
| Parameter | Default | Example | Effect |
|---|---|---|---|
index |
True |
index=False |
Prevents writing the row index as the first column. |
sep |
"," |
sep=";" or sep="\t" |
Sets the field delimiter (e.g., semicolon for European locales or tab for TSV). |
encoding |
"utf-8" |
encoding="utf-8-sig" |
Controls character encoding (utf-8-sig ensures clean rendering in Excel). |
na_rep |
"" |
na_rep="NULL" |
Controls how NaN / None missing values are represented in the output. |
float_format |
None |
float_format="%.2f" |
Formats floating-point numbers to a fixed number of decimal places. |
mode |
"w" |
mode="a" |
"w" overwrites the file; "a" appends rows to the end of an existing file. |
You must log in or register to comment.