Data usually lives in files: CSV, Excel, JSON, or databases. pandas has a read_* function to load each format into a DataFrame and a to_* method to save it back.
Prerequisites
Read a CSV File
import pandas as pd
df = pd.read_csv('students.csv')
print(df.head())
Useful read_csv Options
df = pd.read_csv(
'sales.csv',
sep=',', # delimiter, e.g. ';' or '\t'
usecols=['date', 'amount'],
parse_dates=['date'],
na_values=['NA', '-'],
nrows=1000,
encoding='utf-8'
)
| Option | Use |
|---|---|
| sep | Delimiter character |
| header | Row number of the header, or None |
| names | Give your own column names |
| index_col | Use a column as the index |
| usecols | Load only some columns |
| dtype | Force column types |
| parse_dates | Convert columns to datetime |
| na_values | Extra values to treat as missing |
| nrows / skiprows | Load part of the file |
| chunksize | Read a huge file in pieces |
Read from a URL
url = 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv'
tips = pd.read_csv(url)
print(tips.shape)
Explanation: read_csv accepts web addresses. This is the public “tips” dataset used by seaborn.
Write a CSV File
df.to_csv('output.csv', index=False)
index=False, otherwise the index is saved as an extra unnamed column.Excel Files
# pip install openpyxl
df = pd.read_excel('report.xlsx', sheet_name='Sheet1')
df.to_excel('result.xlsx', index=False)
all_sheets = pd.read_excel('report.xlsx', sheet_name=None) # dict of DataFrames
JSON, SQL and Others
df = pd.read_json('data.json')
df.to_json('out.json', orient='records', indent=2)
import sqlite3
con = sqlite3.connect('school.db')
df = pd.read_sql('SELECT * FROM students', con)
df.to_sql('students_copy', con, if_exists='replace', index=False)
df.to_parquet('data.parquet') # fast columnar format, needs pyarrow
Large Files in Chunks
total = 0
for chunk in pd.read_csv('big.csv', chunksize=100_000):
total += chunk['amount'].sum()
print(total)
Common Errors
| Problem | Cause and fix |
|---|---|
UnicodeDecodeError |
Try encoding=’latin-1′ or ‘cp1252’ for files from Excel on Windows. |
ParserError: Error tokenizing data |
Wrong separator or broken rows; set sep, or on_bad_lines=’skip’. |
ImportError: Missing optional dependency 'openpyxl' |
pip install openpyxl. |
| Extra “Unnamed: 0” column | The file was saved with its index. Use index_col=0 or save with index=False. |
Practice Exercises
- Load the tips dataset and save only rows with tip > 5 to a new CSV.
- Read just the first 100 rows of a large file.
Interview Questions
Q: Why use index=False in to_csv?
To avoid writing the index as an extra column.
Q: How to read a file too big for memory?
Use chunksize, usecols, or dtypes to reduce memory.
Summary
Load data with read_csv/read_excel/read_json/read_sql, use options like usecols and parse_dates, and save with to_csv(index=False) and friends.
Next: JSON and API Data · Missing Data
Machine Learning Tutorials, Courses and Certifications