How to Export Pandas DataFrames to CSV and Excel in Python
After cleaning, transforming, or analyzing your dataset in pandas, you’ll often want to save your results to use later or share with others. Luckily, pandas makes exporting DataFrames easy.
Step 1: Exporting to CSV
The most common format is CSV. Use the .to_csv()
method:
import pandas as pd
# Example DataFrame
data = {
"Country": ["Canada", "USA", "Mexico"],
"Population": [38, 331, 128]
}
df = pd.DataFrame(data)
# Export to CSV
df.to_csv("output.csv", index=False)
👉 index=False
prevents pandas from writing the row numbers (0, 1, 2) as a separate column.
Step 2: Exporting to Excel
For Excel files:
df.to_excel("output.xlsx", index=False)
👉 This requires the openpyxl
library (install with pip install openpyxl
).
Step 3: Exporting with Custom Options
Change delimiter (e.g., use
;
instead of,
):df.to_csv("output_semicolon.csv", sep=";", index=False)
Export only selected columns:
df[["Country"]].to_csv("countries_only.csv", index=False)
Quick Recap
Use
.to_csv("filename.csv", index=False)
to save as CSV.Use
.to_excel("filename.xlsx", index=False)
to save as Excel.Customize output with options like
sep
and column selection.
✅ You’ve now learned the full cycle: loading → selecting → exporting data in pandas. From here, you can move on to more advanced topics like filtering rows, cleaning missing data, and creating summary statistics.
👉 Go back to the first tutorial: How to Read a CSV or Excel File in Python with Pandas