Saving Pandas Dataframe as CSV

Arrays | File handling | NumPy | Python Methods and Functions

Most of the datasets you work with are named DataFrames. DataFrames — it is a two-dimensional labeled data structure with an index for rows and columns, where each cell is used to store a value of any type. Essentially, DataFrames — it is a dictionary based on NumPy arrays.

Let`s see how to save a Pandas DataFrame as a CSV file using to_csv () .

Example # 1: Save CSV to working directory.

# import 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 ]

 
# list dictionary

dict = { `name` : nme, `degree` : deg, ` score` : scr} 

  

df = pd.DataFrame ( dict )

 
# save data frame

df.to_csv ( `file1.csv` )

Output:

Example # 2: Saving CSV without headers and index .

# import 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 ]

 
# list dictionary

dict = { `name` : nme, `degree` : deg, ` score` : scr} 

 

df = pd.DataFrame ( dict )

 
# save data frame

df.to_csv ( `file2.csv` , header = Fals e , index = False )

Output:

Example # 3: Save the CSV file to the specified place.

# import pandas as pd

import pandas as pd 

 
# list of name, degree, points

nme = [ "aparna" , "pankaj" , "sudhir" , < / code> "Geeku" ]

deg = [ "MBA" , "BCA" , "M.Tech" , "MBA" ]

scr = [ 90 , 40 , 80 , 98 ]

 
# list dictionary

dict = { `name` : nme, ` degree` : deg, `score ` : scr} 

  

df = pd.DataFrame ( dict )

 
# save frame data

df.to_csv (r `C: UsersAdminDesktopfile3.csv` , index = False )

Output:





Get Solution for free from DataCamp guru