XII IP CH 4 Importing Exporting
XII IP CH 4 Importing Exporting
– to_csv()
Write a dataframe's data to a CSV file.
Reading from a CSV file to DataFrame
• Consider a file Example1.csv stored in G: drive
import pandas as pd
df=pd.read_csv("G:\\Example2.csv", header=None)
print(df)
Specifying column headings
If the CSV file does not contain headings, then
import pandas as pd
df=pd.read_csv("G:\\Example2.csv",
names=["Rollno", "FirstName", "LastName"])
print(df)
Specifying column headings
If the CSV file contains headings, then
import pandas as pd
df=pd.read_csv("G:\\Example1.csv",
names=["Country", "Code", "Year",
"Population"], skiprows=1)
print(df)
sep argument
• Some csv files are so created that their
separator character is different from comma
such as ; | tab(\t), etc.
df=pd.read_csv("G:\\Example3.csv", sep=';')
df=pd.read_csv("G:\\Example3.csv", sep='\t')
Get DataFrame Index labels from CSV
import pandas as pd
df=pd.read_csv("G:\\Example3.csv",
index_col="Empno")
print(df)
Storing DataFrame's Data to CSV File
• Function to_csv() can be used to save the data
of a DataFrame to a CSV file.
<DF>.to_csv(<filepath>)
<DF>.to_csv(<filepath>, sep=<separator char>)
d={'Rollno':[101,102,103,104],
'Name':['Ani','Amna','Arjan','Mark'],
'Surname':['Kapur','Sharif','Singh','Robin']}
df=pd.DataFrame(d)
print(df)
df.to_csv("G:\\student.csv")