Skip to content
Related Articles
Open in App
Not now

Related Articles

Saving a Pandas Dataframe as a CSV

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 03 Oct, 2022
Improve Article
Save Article

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. 

Creating DataFrame to Export Pandas DataFrame to CSV

Python3




# 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)
 
print(df)


Output:

     name  degree  score
0  aparna     MBA     90
1  pankaj     BCA     40
2  sudhir  M.Tech     80
3   Geeku     MBA     98

Export CSV to a working directory

Here, we simply export a Dataframe to a CSV file using df.to_csv().

Python3




# saving the dataframe
df.to_csv('file1.csv')


Output:

Saving a Pandas Dataframe as a CSV

 

   

Saving CSV without headers and index

Here, we are saving the file with no header and no index number.

Python3




# saving the dataframe
df.to_csv('file2.csv', header=False, index=False)


Output:

Saving a Pandas Dataframe as a CSV

 

   

Save the CSV file to a specified location

We can also, save our file at some specific location.

Python3




# 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” .

Python3




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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!