Python - How to write pandas dataframe to a CSV file



To write pandas dataframe to a CSV file in Python, use the to_csv() method. At first, let us create a dictionary of lists −

# dictionary of lists d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22'] }

Now, create pandas dataframe from the above dictionary of lists −

dataFrame = pd.DataFrame(d) 

Our output CSV file will generate on the Desktop since we have set the Desktop path below −

dataFrame.to_csv("C:\Users\amit_\Desktop\sales1.csv\SalesRecords.csv")

Example

Following is the code −

import pandas as pd # dictionary of lists d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22'] } # creating dataframe from the above dictionary of lists dataFrame = pd.DataFrame(d) print("DataFrame...\n",dataFrame) # write dataFrame to SalesRecords CSV file dataFrame.to_csv("C:\Users\amit_\Desktop\SalesRecords.csv") # display the contents of the output csv print("The output csv file written successfully and generated...")

Output

This will produce the following output −

DataFrame...         Car Date_of_purchase 0       BMW 2020-10-10 1     Lexus 2020-10-12 2      Audi 2020-10-17 3  Mercedes 2020-10-16 4    Jaguar 2020-10-19 5   Bentley 2020-10-22 The output csv file written successfully and generated...

The resultant “SalesRecords.csv” generated successfully with the following records i.e., pandas dataframe −

Updated on: 2021-10-04T07:16:22+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements