Sub topic 3
Reading One Sheet or All Sheets
Assume you know basic Python, can install packages, and understand DataFrames, CSV files, and spreadsheets. This chapter focuses on choosing the correct part of an Excel workbook and checking the result.
Reading one sheet or all sheets
Use sheet_name to select a worksheet. It accepts a sheet name or a zero-based sheet number.
import pandas as pd
sales = pd.read_excel("report.xlsx", sheet_name="Sales")
first_sheet = pd.read_excel("report.xlsx", sheet_name=0)
workbook = pd.read_excel("report.xlsx", sheet_name=None)
for name, frame in workbook.items():
print(name, frame.shape)With sheet_name=None, pandas returns a dictionary whose keys are sheet names and whose values are DataFrames.
Skipping rows and picking column ranges in Excel
Reports often begin with a title, notes, or blank lines. Use skiprows to ignore them. Use usecols to select Excel column letters, and nrows to limit the number of data rows.
summary = pd.read_excel(
"report.xlsx",
sheet_name="Summary",
skiprows=2,
usecols="A:C",
nrows=10,
)Check whether the selected range includes the actual header. If the header is elsewhere, set header to its zero-based row number, or use header=None when there is no header.
Excel engines and file formats
Pandas delegates spreadsheet parsing to an engine.
| Format | Common engine | Package |
|---|---|---|
| `.xlsx` | `openpyxl` | `pip install openpyxl` |
| `.xls` | `xlrd` | `pip install xlrd` |
Fixing encoding errors and bad lines
Encoding problems apply mainly to CSV files. Try the file's real encoding, such as latin-1, rather than changing data blindly. For malformed rows, choose a deliberate policy.
df = pd.read_csv(
"legacy.csv",
encoding="latin-1",
on_bad_lines="skip",
)Skipping rows can hide data loss. Prefer fixing the source or recording which rows were rejected.
Reading large CSV files in chunks
chunksize returns an iterator of smaller DataFrames. Aggregate each chunk instead of loading the complete file.
total = 0
for chunk in pd.read_csv("events.csv", usecols=["amount"], chunksize=100_000):
total += chunk["amount"].sum()
print(total)Validating a loaded DataFrame
Inspect structure before analysis:
print(df.head())
print(df.dtypes)
df.info()Confirm expected columns, row counts, data types, and missing values. A successful read does not prove that the data is correct.
Exercise
How do you load every worksheet in an Excel workbook?
Show answer
Use pd.read_excel("report.xlsx", sheet_name=None), which returns a dictionary of DataFrames keyed by sheet name.