Writing DataFrames to Files
Export a cleaned DataFrame to CSV and Excel with to_csv and to_excel, controlling the index and float format.
Why Export Matters
Data analysis rarely ends inside Python. You need to share cleaned datasets with stakeholders, feed results into other tools, or archive processed data for reproducibility. Pandas provides to_csv(), to_excel(), to_json(), and to_parquet() — mirroring the read functions and accepting most of the same configuration parameters.
import pandas as pd
df = pd.DataFrame({'name': ['A', 'B'], 'score': [90, 75]})
df.to_csv('results.csv')
df.to_excel('results.xlsx')
df.to_json('results.json', orient='records')to_csv(): The Index Gotcha
By default to_csv() writes the row index as the first column, creating an unnamed: 0 column when you read the file back. Pass index=False to omit the index — almost always the right choice unless the index itself is meaningful data (like dates). Always specify index=False unless you have a deliberate reason to include the index.
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
# Include index (default -- creates 'Unnamed: 0' when re-read)
df.to_csv('with_index.csv')
# Exclude index (recommended)
df.to_csv('clean.csv', index=False)All lessons in this course
- Reading CSV Files
- Reading Excel and JSON Files
- Writing DataFrames to Files
- Reading from URLs and StringIO