How to Export Pandas DataFrame to a CSV File

Say that you want to export pandas DataFrame to a CSV file.

How would you go about it?

In a nutshell, you can use the following structure in Python in order to export your pandas DataFrame to a CSV file:

df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv')

But wait a minute, how can you apply the above structure in practice?

Worry no more, as I’ll show you a full example, where:

  • First, I’ll create a DataFrame from scratch
  • Then, I’ll show you how to export that DataFrame into a CSV file

So let’s start by reviewing a simple example.

Example used to export pandas DataFrame to a CSV file

Ok, so let’s say that you have the following data about cars:

BrandPrice
Honda Civic22,000
Toyota Corolla25,000
Ford Focus27,000
Audi A435,000

How would you create a DataFrame in Python for that data?

(1) First thing first, you’ll need to import the pandas module. You may install the pandas module using the PIP method

(2) Then you can create the DataFrame based on the following code:

 

from pandas import DataFrame

Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

df = DataFrame(Cars, columns= ['Brand', 'Price'])

print (df)

 

Now say that you want to export the DataFrame you just created to a CSV file.

In my case, I decided to export the DataFrame to my desktop. This is the path that I used:

r‘C:\Users\Doron E\Desktop\export_dataframe.csv

Notice that I highlighted a portion of the path with 3 different colors:

  • The yellow part represents the r character that you should place before the path name (to take care of any symbols within the path name, such as the backslash symbol). Otherwise, you’ll get the following error: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape
  • The blue part represents the file name to be created. You may type a different file name if you’d like
  • The green part represents the file type, which is ‘csv.’ You must add that portion anytime you want to export your DataFrame to a CSV file. Alternatively, you may use the file type of ‘txt’ if you want to export your DataFrame to a Text file

Before you run the code below, you’ll need to modify the export path to the location where you’d like to store the CSV file on your computer.

And here is the full Python code:

 

from pandas import DataFrame

Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

df = DataFrame(Cars, columns= ['Brand', 'Price'])

export_csv = df.to_csv (r'C:\Users\Doron E\Desktop\export_dataframe.csv', index = None, header=True) #Don't forget to add '.csv' at the end of the path

print (df)

 

That’s it! Once you run the Python code, the CSV file will be saved at your specified location.

In the final section (optional), I’ll show you how to export pandas DataFrame to a CSV file using the tkinter module.

Export pandas DataFrame to a CSV file using tkinter

In the example we just saw, you needed to specify the export path within the code itself.

But what if I told you that there is a way to export your DataFrame without the need to input any path within the code.

Instead, you may use the following universal code that will allow you to choose the export location using a dialogue box.

So here is the code:

 

import tkinter as tk
from tkinter import filedialog
from pandas import DataFrame

Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

df = DataFrame(Cars, columns= ['Brand', 'Price'])


root= tk.Tk()

canvas1 = tk.Canvas(root, width = 300, height = 300, bg = 'lightsteelblue2', relief = 'raised')
canvas1.pack()

def exportCSV ():
    global df
    
    export_file_path = filedialog.asksaveasfilename(defaultextension='.csv')
    df.to_csv (export_file_path, index = None, header=True)

saveAsButton_CSV = tk.Button(text='Export CSV', command=exportCSV, bg='green', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 150, window=saveAsButton_CSV)

root.mainloop()

 

Make sure to adjust the code to your desired DataFrame. Simply replace the DataFrame (that captures the ‘cars’ data) with your own tailored DataFrame.

But for the time being, if you run the above code, the following tkinter GUI will be displayed:

 

How to Export Pandas DataFrame to a CSV File

 

Click on the ‘Export CSV’ button.

You’ll see a dialogue box that will allow you to choose the export location.

Simply type the name of your desired file (here I chose to name the file as ‘Cars’), and then press Save:

 

Export Pandas DataFrame to a CSV File

 

Your CSV file will be saved at to your chosen location in a shiny manner.

Conclusion

We just saw the steps needed to create a DataFrame and then export that DataFrame to a CSV file.

You may face an opposite scenario in which you’ll need to import a CSV into Python. If that’s the case, you can check this tutorial that explains how to import a CSV file into Python using pandas.

You may also want to check the pandas documentation for further information about using ‘to_csv’.