Last Updated : 15 Jul, 2025
When working on a Data Science project one of the key tasks is data management which includes data collection, cleaning and storage. Once our data is cleaned and processed it’s essential to save it in a structured format for further analysis or sharing.
A CSV (Comma-Separated Values) file is a widely used format for storing tabular data. In Python Pandas provides an easy-to-use function to_csv()
to export a DataFrame into a CSV file. This article will walk we through the process with step-by-step examples and customizations.
Before exporting let's first create a sample DataFrame using Pandas.
Python
import pandas as pd
scores = {'Name': ['a', 'b', 'c', 'd'],
'Score': [90, 80, 95, 20]}
df = pd.DataFrame(scores)
print(df)
Output :
Now that we have a sample DataFrame, let's export it to a CSV file.
Exporting DataFrame to CSV 1. Basic ExportThe simplest way to export a DataFrame to a CSV file is by using the to_csv()
function without any additional parameters. This method creates a CSV file where the DataFrame's contents are written as-is.
df.to_csv("your_name.csv")
Output
File Successfully saved Customizing the CSV Export 2. Remove Index ColumnThe
to_csv()
exports the index column which represents the row numbers of the DataFrame. If we do not want this extra column in our CSV file we can remove it by setting index=False
.
df.to_csv('your_name.csv', index = False)
Output :
In some cases we may not want to export all columns from our DataFrame. The columns
parameter in to_csv()
allows us to specify which columns should be included in the output file.
df.to_csv("your_name.csv", columns = ['Name'])
Output :
By default theto_csv()
function includes column names as the first row of the CSV file. However if we need a headerless file e.g., for certain machine learning models or integration with other systems we can set header=False
.
df.to_csv('your_name.csv', header = False)
Output :
DataFrames often contain missing values (NaN
) which can cause issues in downstream analysis. By default Pandas writes NaN
as an empty field but we can customize this behavior using the na_rep
parameter.
df.to_csv("your_name.csv", na_rep = 'nothing')
6. Change Column Separator
CSV files use commas (,
) by default as delimiters to separate values. However in some cases other delimiters may be required such as tabs (), semicolons (;
), or pipes (|
). Using a different delimiter can make the file more readable or compatible with specific systems.
df.to_csv("your_name.csv", sep ='\t')
Output :
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4