Sub topic 9
Reading one sheet or all sheets
This chapter assumes you know how to call pd.read_excel on a single file, that you have openpyxl installed for .xlsx files, and that you know what a DataFrame is. Here you learn how to choose which sheets of a workbook become DataFrames.
How sheet_name works
A workbook can hold many sheets. By default, read_excel reads only the first one and returns a single DataFrame. The sheet_name argument changes that. Its value decides both which sheets are read and what type of object you get back.
| `sheet_name` value | Result |
|---|---|
| `0` (default) | DataFrame of the first sheet |
| `"Feb"` | DataFrame of the sheet named Feb |
| `1` | DataFrame of the second sheet (positions start at 0) |
| `["Jan", "Feb"]` | Dict of DataFrames keyed by the items you gave |
| `None` | Dict of DataFrames for every sheet |
The type of the result depends on the value you pass. A single name or number returns a DataFrame. A list or None returns a dict. Code that assumes one or the other fails with confusing errors, so check which case you are in.
Listing sheets before reading
You often need to see the sheet names first. pd.ExcelFile opens the workbook once and lets you list names and parse several sheets from the same open file. The example below builds a small two-sheet workbook in memory so it runs without any file on disk.
import pandas as pd
from io import BytesIO
buffer = BytesIO()
with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
pd.DataFrame({"sales": [1, 2]}).to_excel(writer, sheet_name="Jan", index=False)
pd.DataFrame({"sales": [3, 4]}).to_excel(writer, sheet_name="Feb", index=False)
buffer.seek(0)
with pd.ExcelFile(buffer) as xls:
print(xls.sheet_names)
feb = xls.parse("Feb")
print(feb)sheet_names prints ['Jan', 'Feb']. xls.parse("Feb") accepts the same arguments as read_excel, such as skiprows and usecols. Using the with block closes the file when you are done.
Reading every sheet at once
When you want all sheets, pass sheet_name=None. You get a dict. Each key is a sheet name and each value is a DataFrame.
import pandas as pd
sheets = pd.read_excel("report.xlsx", sheet_name=None)
for name, frame in sheets.items():
print(name, frame.shape)Each sheet is parsed on its own, so each DataFrame can have different columns and dtypes. Any other arguments, such as dtype or na_values, apply to every sheet.
A common next step is to stack sheets that share a layout, for example one sheet per month. Use pd.concat with the dict. The keys become the outer level of the index, so you can tell where each row came from.
import pandas as pd
sheets = pd.read_excel("report.xlsx", sheet_name=None)
combined = pd.concat(sheets, names=["sheet", "row"])
print(combined.head())Use combined.reset_index(level="sheet") if you prefer the sheet name as an ordinary column.
Common errors
ValueError: Worksheet named 'x' not found: the name does not match. Names are case-sensitive and may contain trailing spaces. Printxls.sheet_namesto see the exact spelling.IndexErroror a "sheet index out of range" error: you passed a position larger than the number of sheets minus one.AttributeError: 'dict' object has no attribute 'head': you passed a list orNoneand got a dict. Pick a sheet withsheets["Feb"].- Slow reads on big workbooks:
read_excelcalled repeatedly on the same file reopens and reparses it each time. Open it once withExcelFileand callparsefor each sheet.
Exercise
A workbook has sheets named "Jan", "Feb" and "Mar". You run data = pd.read_excel("sales.xlsx", sheet_name=["Jan", "Mar"]) and then data.head(). What happens, and how do you get the first rows of the March sheet?
Show answer
data is a dict with the keys "Jan" and "Mar", so data.head() raises an AttributeError because dict has no head method. Use data["Mar"].head() to see the first rows of the March sheet.