Write a Pandas DataFrame to a CSV File

In this tutorial, we will learn how to write a Pandas DataFrame to a CSV file with the help of example? By Pranit Sharma Last updated : April 12, 2023


Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data. DataFrame can be created with the help of python dictionaries or lists but in the real world, CSV files are imported and then converted into DataFrames. Sometimes, DataFrames are first written into CSV files. Here, we are going to write a DataFrame into a CSV file.

What is a CSV File?

CSV files or Comma Separated Values files are plain text files but the format of CSV files is tabular. As the name suggests, in a CSV file, each specific value inside the CSV file is generally separated with a comma. The first line identifies the name of a data column. The further subsequent lines identify the values in rows.

Here, the separator character (,) is called the delimiter. There are some more popular delimiters. E.g.: tab(\t), colon (:), semi-colon (;) etc.

How to Write a Pandas DataFrame to a CSV File?

To write a Pandas DataFrame to a CSV file, use DataFrame.to_csv() method and pass the path of the specified folder where you want to write the CSV file. This method writes the object to a comma-separated values (CSV) file.


Here is the syntax that should be followed to write a DataFrame to a CSV file,


Let us understand with the help of an example.

Python Code to Write a Pandas DataFrame to a CSV File

# Importing pandas package
import pandas as pd

# Creating a dictionary of student marks
d = {

# Now, Create DataFrame
df = pd.DataFrame(d)

# Printing the original DataFrame
print("Original DataFrame:\n")

# Now, Create a csv file and load it 
# into a specified folder
df.to_csv("F:\All study\my_csv.csv")

print("CSV file created\n")
print("Importing this csv file:\n\n")

# We can check the csv file by navigating into the specified 
# folder or by importing it through pd.read_csv()
data = pd.read_csv("F:\All study\my_csv.csv")

# Printing the Data


Write a pandas DataFrame to CSV file | Output

Python Pandas Programs »

All Python Pandas Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.