Skip to main content
Export-Pandas-DataFrame-to-CSV

How to Export Pandas DataFrame to CSV

in this python tutorial, I’ll share the python script to export dataframe into CSV format. Pandas is an open-source library that is built on top of the NumPy library.

CSV(comma-separated values) is the most common file format for storing plain text data. It is one of the most widely used data exchange formats between servers. Each data value is separated by a comma in the CSV files.

Exporting the DataFrame into a CSV file

The to_csv() method in Pandas exports a DataFrame to CSV format. The output will be a CSV file if a file option is provided. Otherwise, the return value is a string in CSV format.

What is Pandas DataFrame

Pandas DataFrames produce a data structure in Excel with labeled axes (rows and columns). To create a DataFrame, you’ll need at least the data rows and column names as header.

The sample example:

NameAge
John34
Saroj29
Adam24

Python Script To save Datatframe to CSV

Let’s create a python script that’ll save panda’s dataframe into the CSV.

import pandas as p 
   
# list of name, age
emp_name = ["John", "Saroj", "Adam"]
age = [34, 29, 24]
   
# dictionary of lists 
dict = {'name': emp_name, 'age': age} 
     
df = p.DataFrame(dict)

# saving the dataframe
df.to_csv('file_name.csv')

Let’s have a look at some of the program’s key features:

  • Step 1: Defined emp_name and age list.
  • Step 2: Created dict using above list.
  • Step 3: Created dataframe using DataFrame() method.
  • Step 4: save pandas dataframe into CSV using to_csv() method

Let’s have a look at some common examples for Dataframe To CSV

Save CSV in relative path

saving the csv file into the relative path.

dt.to_csv('C:/Users/abc/Desktop/file_name.csv')

Custom Separator

we are passing separator tab.

dt.to_csv('file_name.csv',sep='\t')

Set missing value

We are setting the missing value is NAN.

dt.to_csv('file_name.csv',na_rep='NAN')

Enable Row Index

We can also enable/disable row index.

dt.to_csv('file_name.csv',index=False)

Leave a Reply

Your email address will not be published. Required fields are marked *