How to Export Pandas DataFrame to a CSV File

In order to export Pandas DataFrame to a CSV file in Python:

df.to_csv(r"Path to store the exported CSV file\File Name.csv", index=False)

And if you wish to include the index, then simply remove “, index=False” from the code:

df.to_csv(r"Path to store the exported CSV file\File Name.csv")

Steps to Export Pandas DataFrame to a CSV file

Step 1: Install Pandas

Firstly, install the Pandas package (if you haven’t already done so):

pip install pandas

Step 2: Create a DataFrame

Then, create a DataFrame like in the example below:

import pandas as pd

data = {"name": ["laptop", "tablet", "keyboard", "Desk"],
        "brand": ["A", "B", "C", "D"],
        "price": [1200, 350, 100, 500]
        }

df = pd.DataFrame(data)

print(df)

The resulted DataFrame:

       name brand  price
0    laptop     A   1200
1    tablet     B    350
2  keyboard     C    100
3      Desk     D    500

Step 3: Export the DataFrame to a CSV file

To export the DataFrame created to a CSV file (make sure to modify the path to reflect the location where the CSV file would be stored on your computer):

import pandas as pd

data = {"name": ["laptop", "tablet", "keyboard", "Desk"],
        "brand": ["A", "B", "C", "D"],
        "price": [1200, 350, 100, 500]
        }

df = pd.DataFrame(data)

df.to_csv(r"C:\Users\Ron\Desktop\Test\products.csv", index=False)

print(df)

Notice that the following path was used in the example above:

r“C:\Users\Ron\Desktop\Test\products.csv

Where:

  • The yellow part represents the r letter that you should place before the path name (to avoid any unicode errors)
  • The blue part reflects the file name to be created. You may type a different file name based on your needs
  • 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

Note that if you wish to include the index, then simply remove “, index=False” from the code above.

Additional Resources

You 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’.

Leave a Comment