How to export DataFrame to CSV in Python

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. This is similar to a spreadsheet or SQL table, or a dict of Series objects.
A Comma Separated Values (CSV) file is a plain text file that contains a list of data that uses a comma to separate values. Each line of the file is a data record.
In this article, we will see how to export DataFrame to CSV in Python
Let’s create a dummy dataframe first:
import pandas as pd cars = {'Brand': ['Honda Civic', 'Ford Focus', 'Audi A4', 'Toyota Corolla'], 'Price': [220000, 250000, 290000, 340000]} df = pd.DataFrame(cars, columns = ['Brand', 'Price']) print(df)
So we’ve created our dummy dataframe. Now let’s take a look at how this is exported to csv file. For this purpose, we are using the to_csv()
function in the Pandas module.
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
import pandas as pd cars = {'Brand': ['Honda Civic', 'Ford Focus', 'Audi A4', 'Toyota Corolla'], 'Price': [220000, 250000, 290000, 340000]} df = pd.DataFrame(cars, columns = ['Brand', 'Price']) df.to_csv (r'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.