In this article, we will learn how we can export a Pandas DataFrame to a CSV file by using the Pandas to_csv() method. By default, the to csv() method exports DataFrame to a CSV file with row index as the first column and comma as the delimiter.
Table of Content
Here, we are taking sample data to convert DataFrame to CSV.
# importing pandas as pd import pandas as pd # list of name, degree, score nme = ["aparna", "pankaj", "sudhir", "Geeku"] deg = ["MBA", "BCA", "M.Tech", "MBA"] scr = [90, 40, 80, 98] # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr} df = pd.DataFrame(dict)
Export CSV to a Working Directory
Here, we simply export a Dataframe to a CSV file using df.to_csv().
# saving the dataframe df.to_csv('file1.csv')
Output:

Saving CSV Without Headers and Index
Here, we are saving the file with no header and no index number.
# saving the dataframe df.to_csv('file2.csv', header=False, index=False)
Output:

Save the CSV file to a Specified Location
We can also, save our file at some specific location.
# saving the dataframe df.to_csv(r'C:\Users\Admin\Desktop\file3.csv')
Output:

Write a DataFrame to CSV file using Tab Separator
We can also save our file with some specific separate as we want. i.e, "\t" .
import pandas as pd import numpy as np users = {'Name': ['Amit', 'Cody', 'Drew'], 'Age': [20,21,25]} #create DataFrame df = pd.DataFrame(users, columns=['Name','Age']) print("Original DataFrame:") print(df) print('Data from Users.csv:') df.to_csv('Users.csv', sep='\t', index=False,header=True) new_df = pd.read_csv('Users.csv') print(new_df)
Output:
Original DataFrame:
Name Age
0 Amit 20
1 Cody 21
2 Drew 25
Data from Users.csv:
Name\tAge
0 Amit\t20
1 Cody\t21
2 Drew\t25