You can use the following template 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', index=False)
And if you wish to include the index, then simply remove “, index=False” from the code:
df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv')
Next, you’ll see a full example, where:
- A DataFrame will be created from scratch
- Then, the DataFrame will be exported to a CSV file
Example used to Export Pandas DataFrame to a CSV file
Let’s say that you have the following data about products:
product | price |
computer | 850 |
tablet | 200 |
printer | 150 |
laptop | 1300 |
How would you create a DataFrame in Python for that data?
Firstly, you’ll need to install the Pandas package (if you haven’t already done so):
pip install pandas
Then, you’ll be able to create a DataFrame based on the following code:
import pandas as pd data = {'product': ['computer', 'tablet', 'printer', 'laptop'], 'price': [850, 200, 150, 1300] } df = pd.DataFrame(data) print(df)
Now let’s say that you want to export the DataFrame you just created to a CSV file.
For example, let’s export the DataFrame to the following path:
r‘C:\Users\Ron\Desktop\export_dataframe.csv‘
Notice that 3 portions of the path were highlighted with 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)
- The blue part represents the file name to be created. You may type a different file name if you wish
- 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 path to reflect the location where you’d like to store the CSV file on your computer.
And here is the full Python code:
import pandas as pd data = {'product': ['computer', 'tablet', 'printer', 'laptop'], 'price': [850, 200, 150, 1300] } df = pd.DataFrame(data) df.to_csv(r'C:\Users\Ron\Desktop\export_dataframe.csv', index=False, header=True) print(df)
Once you run the Python code, the CSV file will be saved at your specified location.
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’.