📊 Unit 1 – DataFrame · Lesson 11
Importing & Exporting CSV
What is a CSV file?
A CSV (comma-separated values) file stores a table as plain text – one row per line, values separated by commas. Excel, Google Sheets and MySQL can all open and save CSV, so it is the easiest way to move data into pandas.
Export: to_csv()
Python
import pandas as pd
df = pd.DataFrame({'Roll': [1, 2, 3, 4], 'Name': ['Asha', 'Ravi', 'Neha', 'Om'],
'Maths': [78, 92, 65, 88], 'IP': [88, 81, 95, 74]})
df.to_csv('result.csv', index=False) # export without the row index
print(open('result.csv').read())Roll,Name,Maths,IP
1,Asha,78,88
2,Ravi,92,81
3,Neha,65,95
4,Om,88,74
Import: read_csv()
Python
import pandas as pd
df = pd.read_csv('result.csv') # import
print(df)
print(df.shape, df.columns.tolist()) Roll Name Maths IP
0 1 Asha 78 88
1 2 Ravi 92 81
2 3 Neha 65 95
3 4 Om 88 74
(4, 4) ['Roll', 'Name', 'Maths', 'IP']
Useful read_csv options
| Parameter | Use |
|---|---|
| sep | Separator character (default ",") |
| header | Row number of column names; None if there is no header |
| names | List of column names to use |
| index_col | Column to use as the row index |
| usecols | Read only these columns |
| nrows | Read only the first n rows |
Python
import pandas as pd
df = pd.read_csv('result.csv', index_col='Roll') # use a column as row index
print(df)
print(pd.read_csv('result.csv', usecols=['Name', 'IP'], nrows=2)) Name Maths IP
Roll
1 Asha 78 88
2 Ravi 92 81
3 Neha 65 95
4 Om 88 74
Name IP
0 Asha 88
1 Ravi 81
File without a header row
Python
import pandas as pd
with open('nohead.csv', 'w') as f:
f.write('101,Pen,10\n102,Pencil,5\n103,Eraser,3\n')
items = pd.read_csv('nohead.csv', header=None, names=['Code', 'Item', 'Price'])
print(items) Code Item Price
0 101 Pen 10
1 102 Pencil 5
2 103 Eraser 3
Other separators
Python
import pandas as pd
df = pd.read_csv('result.csv')
df.to_csv('result_semicolon.csv', sep=';', index=False)
print(open('result_semicolon.csv').read().splitlines()[:2])
back = pd.read_csv('result_semicolon.csv', sep=';')
print(back.head(2))['Roll;Name;Maths;IP', '1;Asha;78;88']
Roll Name Maths IP
0 1 Asha 78 88
1 2 Ravi 92 81
Complete CSV program
Python
import pandas as pd
df = pd.read_csv('result.csv')
df['Total'] = df['Maths'] + df['IP']
df['Percent'] = (df['Total'] / 2).round(1)
toppers = df[df['Percent'] >= 82]
toppers.to_csv('toppers.csv', index=False)
print(df)
print('Saved', len(toppers), 'toppers')
print(open('toppers.csv').read()) Roll Name Maths IP Total Percent
0 1 Asha 78 88 166 83.0
1 2 Ravi 92 81 173 86.5
2 3 Neha 65 95 160 80.0
3 4 Om 88 74 162 81.0
Saved 2 toppers
Roll,Name,Maths,IP,Total,Percent
1,Asha,78,88,166,83.0
2,Ravi,92,81,173,86.5
Frequently Asked Questions
Why use index=False in to_csv()?
Without it pandas also writes the row index (0, 1, 2…) as an extra unnamed first column.
How do I read a CSV file that has no header?
Use header=None, and give column names with names=[...].
Where should the CSV file be kept?
In the same folder as the Python program, or give the full path, e.g. pd.read_csv("C:/data/result.csv").
