Module 5: Reading Data
Learning Objectives
By the end of this module, you will be able to:
Read data from CSV, Excel, JSON, SQL, HTML, XML, and Parquet files
Use appropriate parameters for each file format
Handle common import issues (encoding, headers, delimiters)
Understand when to use each format
Introduction
Pandas provides a rich set of I/O functions for reading data from virtually any file format. The general pattern is:
df = pd.read_<format>("path/to/file", parameter1=value1, ...)
Note
For writing data, the corresponding pattern is df.to_<format>("path/to/file").
Reading CSV
CSV (Comma-Separated Values) is the most common data format in data science.
Basic usage
import pandas as pd
df = pd.read_csv("data/sales.csv")
Common parameters
df = pd.read_csv(
"data/sales.csv",
sep=",", # Delimiter (default: ",")
header=0, # Row to use as column names (None = no header)
names=["A", "B", "C"], # Custom column names
index_col=0, # Column to use as row index
usecols=["Name", "Age"], # Only load specific columns
dtype={"Age": int, "Salary": float}, # Specify dtypes
parse_dates=["Date"], # Parse date columns
na_values=["", "NA", "N/A", "NULL"], # Treat as NaN
encoding="utf-8", # File encoding
skiprows=2, # Skip first N rows
nrows=1000, # Only read first 1000 rows
thousands=",", # Thousands separator
)
Tip
When working with large CSV files, use dtypes (specified as a dictionary) combined with nrows for initial exploration. This significantly reduces memory usage and load time.
Handling common CSV issues
# No header row
df = pd.read_csv("data.csv", header=None)
# Custom separator (e.g., tab-separated, semicolon)
df = pd.read_csv("data.tsv", sep="\t")
df = pd.read_csv("data_european.csv", sep=";")
# Encoding issues
df = pd.read_csv("data.csv", encoding="latin-1") # or "cp1252"
# Quoted fields with internal commas
df = pd.read_csv("data.csv", quotechar='"')
Reading Excel
# Read default first sheet
df = pd.read_excel("data/report.xlsx")
# Read a specific sheet
df = pd.read_excel("data/report.xlsx", sheet_name="Sheet2")
# Read multiple sheets
dfs = pd.read_excel("data/report.xlsx", sheet_name=["Sheet1", "Sheet2"])
# Read all sheets
dfs = pd.read_excel("data/report.xlsx", sheet_name=None)
# Additional parameters
df = pd.read_excel(
"data/report.xlsx",
sheet_name=0,
header=1, # Row 1 (0-indexed) contains headers
usecols="A:C, F", # Excel column notation
dtype={"ID": str},
skiprows=3,
)
Warning
pd.read_excel() requires either openpyxl (for .xlsx) or xlrd (for older .xls). Install with:
pip install openpyxl xlrd
## Reading JSON
```python
# Standard JSON
df = pd.read_json("data/data.json")
# JSON lines (one JSON object per line)
df = pd.read_json("data/data.jsonl", lines=True)
# From a string
json_str = '{"Name": ["Alice", "Bob"], "Age": [25, 30]}'
df = pd.read_json(json_str)
Handling nested JSON
import json
# Flatten nested structures
with open("data/nested.json") as f:
data = json.load(f)
df = pd.json_normalize(
data,
record_path="orders", # Path to nested records
meta=["user_id", "name"], # Top-level fields to include
meta_prefix="user_", # Prefix for meta columns
)
Note
pd.json_normalize() is the primary tool for flattening deeply nested JSON into a tabular format. It handles lists of records within records gracefully.
Reading SQL
from sqlalchemy import create_engine
# Create a database connection
engine = create_engine("sqlite:///data/database.db")
# Read SQL query
df = pd.read_sql_query("SELECT * FROM customers WHERE age > 30", engine)
# Read entire table
df = pd.read_sql_table("customers", engine)
# Using read_sql (auto-detects query vs table)
df = pd.read_sql("SELECT * FROM customers", engine)
Connection strings
# SQLite
engine = create_engine("sqlite:///data.db")
# PostgreSQL
engine = create_engine("postgresql://user:password@host:5432/dbname")
# MySQL
engine = create_engine("mysql+pymysql://user:password@host:3306/dbname")
# SQL Server
engine = create_engine("mssql+pyodbc://user:password@host/dbname?driver=ODBC+Driver+17+for+SQL+Server")
Tip
Always close database connections after use, or use a context manager:
with create_engine("sqlite:///data.db").connect() as conn:
df = pd.read_sql("SELECT * FROM table", conn)
## Reading HTML
Pandas can extract tables directly from HTML pages.
```python
# Returns a list of all DataFrames found on the page
tables = pd.read_html("https://en.wikipedia.org/wiki/List_of_countries_by_GDP")
# Select a specific table
df = tables[0]
# Additional parameters
df = pd.read_html(
"page.html",
match="Population", # Find table containing this text
header=0,
attrs={"id": "my-table"}, # Search for a specific HTML attribute
thousands=",",
)
Warning
pd.read_html() requires lxml, html5lib, or BeautifulSoup. These are powerful but sensitive to malformed HTML. Install with:
pip install lxml html5lib beautifulsoup4
## Reading XML
```python
# Simple XML
df = pd.read_xml("data/data.xml", xpath=".//record")
# With attributes
df = pd.read_xml(
"data/data.xml",
xpath=".//book",
attribs=["id", "category"], # Include XML attributes
)
# From string
xml_str = """<?xml version="1.0"?>
<data>
<book id="1">
<title>Python 101</title>
<price>29.99</price>
</book>
</data>"""
df = pd.read_xml(xml_str)
# Write to XML
df.to_xml("output.xml", root_name="data", row_name="record")
Note
pd.read_xml() was introduced in Pandas 1.3 and relies on lxml (recommended) or etree from the standard library.
Reading Parquet
Parquet is a columnar storage format optimised for performance and compression.
# Basic read
df = pd.read_parquet("data/data.parquet")
# With filters (row pruning — only reads matching rows)
df = pd.read_parquet(
"data/data.parquet",
filters=[("year", ">=", 2020), ("region", "==", "EU")],
)
# Only specific columns (column pruning)
df = pd.read_parquet("data/data.parquet", columns=["id", "name", "revenue"])
Tip
Parquet is ideal for large datasets because it is compressed, columnar, and supports predicate pushdown (row filtering at the storage level). It is the recommended format for production data pipelines.
Warning
pd.read_parquet() requires pyarrow or fastparquet:
pip install pyarrow
## Format Comparison
| Format | Speed | Size | Schema | Human-readable | Use case |
|--------|-------|------|--------|----------------|----------|
| CSV | Slow | Large | No | Yes | Interchange, spreadsheets |
| Excel | Slow | Large | Partial | Yes | Business reporting |
| JSON | Medium | Medium | Yes | Yes | Web APIs |
| Parquet | Fast | Small | Yes | No | Production pipelines |
| SQL | Medium | — | Yes | No | Databases |
| HTML | Slow | Large | No | Yes | Web scraping |
| XML | Slow | Large | Yes | Yes | Legacy systems |
## Summary
- Pandas can read from a wide variety of data sources using a consistent `pd.read_*()` API
- CSV is the most common but Parquet offers the best performance for large datasets
- Each format supports format-specific parameters for fine-grained control
- Always specify `dtypes` and `parse_dates` for CSV to avoid type inference issues
## Exercises
1. Download any CSV dataset and read it using `pd.read_csv()` with at least 5 parameters
2. Read an Excel file with multiple sheets and combine them into a single DataFrame
3. Extract a table from any Wikipedia page using `pd.read_html()`
4. Convert a CSV file to Parquet format and compare the file sizes and read speeds
## Further Reading
- [Pandas I/O Documentation](https://pandas.pydata.org/docs/user_guide/io.html)
- [CSV Format Specification](https://tools.ietf.org/html/rfc4180)
- [Apache Parquet Documentation](https://parquet.apache.org/documentation/)