Import data from a CSV file into a DataFrame and export a DataFrame to a CSV file
Expt. No.17
Page No.34
CSV import and export
Aim
To write a Python program that reads a CSV file into a DataFrame, adds a column, and writes the result to a new CSV file.
Concepts used
Algorithm
- Read marks.csv with pd.read_csv() and display it.
- Add a Total column.
- Write the DataFrame to result.csv with to_csv(), leaving out the index.
- Read result.csv back and display it to check.
Program
# Importing and exporting data between CSV files and DataFrames import pandas as pd df = pd.read_csv("marks.csv")print("Read from marks.csv:")print(df) df["Total"] = df["English"] + df["Maths"] + df["IP"]df.to_csv("result.csv", index=False)print("Saved result.csv") check = pd.read_csv("result.csv")print("Read back from result.csv:")print(check)
A marked line continues the line above it. In your file, write it on the same line.
Input file
marks.csv5 lines
Name,English,Maths,IP Asha,82,91,95 Rohan,67,58,72 Ira,88,79,90 Kabir,74,85,81
Output
$ python dataframe_csv_import_export.py
Read from marks.csv:
Name English Maths IP
0 Asha 82 91 95
1 Rohan 67 58 72
2 Ira 88 79 90
3 Kabir 74 85 81
Saved result.csv
Read back from result.csv:
Name English Maths IP Total
0 Asha 82 91 95 268
1 Rohan 67 58 72 197
2 Ira 88 79 90 257
3 Kabir 74 85 81 240
✓ Printed by running this program, not typed by hand.
Contents of result.csv
result.csvafter the run
Name,English,Maths,IP,Total Asha,82,91,95,268 Rohan,67,58,72,197 Ira,88,79,90,257 Kabir,74,85,81,240
Result
read_csv() turned the 4 rows of marks.csv into a DataFrame with a default index. After adding Total, to_csv() wrote result.csv;
index=False kept the row numbers out of the file, as its contents show.Viva voce: what the examiner may ask
01What does index=False do in to_csv()?
It stops the row labels being written as an extra first column.
02Which row of the CSV file becomes the column labels?
The first row (the header).
03How do you read a file whose values are separated by ;?
pd.read_csv("file.csv", sep=";").
Variations for the lab test
- Read only the Name and IP columns with
usecols. - Save the DataFrame with the index and look at the difference in the file.
- Read a CSV file that has no header row using
header=None.
! Common mistake Leaving out
index=False writes the index as an unnamed first column, which appears as "Unnamed: 0" when the file is read again.