How to export a Python DataFrame to a csv file?

In today’s data analysis tutorial we’ll go through a very simple recipe for exporting a Pandas DataFrame to a comma separated value (csv) file. This is specially useful feature that allows us once we finish to clean our raw data to persist the result in a handy file.

Save Pandas DataFrame to file example

Create example data

We’ll start by creating a very simple DataFrame for our example. You can follow along by writing the code into your Python data analysis environment / notebook.

# import the Pandas library into your Python environment
import pandas as pd

# define a dictionary with smaple data
candidates = {'city': ['Atlanta', 'Boston', 'Boston','New York'],
             'office': ['West','East','South','West'],
              'candidates': [190,100,102, 80]*2}

hr = pd.DataFrame(candidates)

Once the DataFrame has been create we can move on to the next step.

Export the Python dataframe to CSV

Saving the data to a comma delimited file is rather simple. We’ll use the the to_csv method that is made available for Pandas DataFrames. We can call the to_csv method and pass the location of the file we’ll export.

hr.to_csv('<your_csv_file_path_name>')

You can easily save the data in other formats such as tsv (tab delimited values).


hr.to_csv('<your_tsv_file_path_name>', sep='\t')

There are a few very useful parameters that you can use to customize your export to csv:

  • columns: Allows you to select which columns will be exported.
  • encoding: Allow to specify a different encoding for your file.

Send Python data to Pickle

You can also go ahead and serialize your data using the pickle format.


hr.to_pickle('<your_pickle_file_path_name>')