Sub topic 9
Reading one sheet or all sheets
This chapter assumes you can already call pd.read_excel on a simple workbook and that an Excel engine such as openpyxl is installed. It covers how the sheet_name argument chooses which sheets to load, what type each choice returns, and how to combine sheets afterwards.
What a workbook gives you
An Excel file (a workbook) holds several sheets, and each sheet is its own grid of cells. A DataFrame holds one table. read_excel therefore has to decide which sheet or sheets to turn into DataFrames. The sheet_name argument makes that choice, and the type of value you pass decides the type of value you get back.
The default is sheet_name=0, which means "the first sheet". If you never pass the argument, you get one DataFrame from the first sheet, whatever its name.
A workbook to practice on
The examples below use a small workbook built in memory, so you can run them without a file. The data variable holds the raw bytes of the workbook. Each read wraps those bytes in a fresh BytesIO, so every call starts at the beginning of the file.
import pandas as pd
from io import BytesIO
buffer = BytesIO()
with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
pd.DataFrame({"region": ["North", "South"], "sales": [10, 20]}).to_excel(
writer, sheet_name="Jan", index=False
)
pd.DataFrame({"region": ["North", "South"], "sales": [30, 40]}).to_excel(
writer, sheet_name="Feb", index=False
)
pd.DataFrame({"note": ["Prepared by finance"]}).to_excel(
writer, sheet_name="Notes", index=False
)
data = buffer.getvalue()
first = pd.read_excel(BytesIO(data))
print(first)The output is the Jan sheet, because it is the first one in the workbook.
Reading one sheet
You can select a single sheet by name or by position.
import pandas as pd
from io import BytesIO
# Assumes `data` from the previous example.
by_name = pd.read_excel(BytesIO(data), sheet_name="Feb")
by_position = pd.read_excel(BytesIO(data), sheet_name=1)
print(by_name.equals(by_position))This prints True, because Feb is the sheet at position 1.
Positions are zero-based, like Python list indexes, so 0 is the first sheet and -1 is not a valid choice in practice. Pick names when you can. A position silently points at a different sheet if someone reorders the tabs, while a name keeps meaning the same sheet.
Both forms fail with a ValueError when the sheet does not exist. The message says that the worksheet name was not found, or that the index is invalid for the number of sheets in the file. The most common cause is a name that differs by a trailing space or by case. Excel treats "Feb " and "Feb" as different names, and so does pandas.
Reading several sheets: a list
If you pass a list, you get back a dictionary. Each key is the item you listed, and each value is a DataFrame.
import pandas as pd
from io import BytesIO
some = pd.read_excel(BytesIO(data), sheet_name=["Jan", "Feb"])
print(type(some))
print(list(some))
print(some["Feb"])
mixed = pd.read_excel(BytesIO(data), sheet_name=["Jan", 2])
print(list(mixed))The first print(list(some)) shows ['Jan', 'Feb']. In the second call the keys are 'Jan' and 2. Keys mirror what you asked for, so if you request a sheet by position, the key is the integer, not the sheet's name. Use names in the list when you want names as keys.
A list with one element still returns a dictionary, not a DataFrame. This catches many people out. If you write sheet_name=["Jan"] and then try df.head(), you will get an AttributeError because df is a dict.
Reading every sheet: None
Passing sheet_name=None reads all sheets and returns a dictionary keyed by sheet name, in workbook order.
import pandas as pd
from io import BytesIO
sheets = pd.read_excel(BytesIO(data), sheet_name=None)
for name, frame in sheets.items():
print(name, frame.shape)Hidden sheets are included, because "hidden" is a display setting in Excel and not a property of the data. Filter the dictionary yourself if you want to exclude any.
Summary of return types
The diagram shows how the value of sheet_name determines what you get.
| `sheet_name` value | Example | Returns | Keys of the dict |
|---|---|---|---|
| Omitted (default `0`) | `read_excel(f)` | DataFrame | not applicable |
| String | `"Feb"` | DataFrame | not applicable |
| Integer | `1` | DataFrame | not applicable |
| List | `["Jan", 2]` | dict | The items in the list |
| `None` | `None` | dict | All sheet names |
Options apply to every sheet you read
When you read more than one sheet in a single call, arguments such as header, skiprows, usecols, dtype and nrows are applied to each sheet in the same way. This is convenient when the sheets share a layout. It causes errors when they do not.
A usecols list of column names raises a ValueError if any sheet lacks one of those columns. In the workbook above, usecols=["region", "sales"] works for Jan and Feb but fails on Notes, which has only a note column.
import pandas as pd
from io import BytesIO
# Works: only the sheets that share the layout are requested.
months = pd.read_excel(
BytesIO(data),
sheet_name=["Jan", "Feb"],
usecols=["region", "sales"],
)
print(months["Jan"].columns.tolist())When the sheets differ, read them in separate calls, each with its own options. The next section shows how to do that without parsing the file again each time.
Reading several times from one file: ExcelFile
Every call to read_excel with a file path opens the workbook and parses it. Opening the same large workbook five times costs five times as much. pd.ExcelFile opens the file once. You then call parse for each sheet, passing the same arguments you would give read_excel.
import pandas as pd
from io import BytesIO
with pd.ExcelFile(BytesIO(data)) as xls:
print(xls.sheet_names)
jan = xls.parse("Jan", usecols=["region", "sales"])
notes = xls.parse("Notes", usecols=["note"])
print(jan)
print(notes)xls.sheet_names is also a handy way to inspect a workbook before you decide what to load, for example to find sheets whose names match a pattern:
import pandas as pd
from io import BytesIO
with pd.ExcelFile(BytesIO(data)) as xls:
month_sheets = [n for n in xls.sheet_names if n in {"Jan", "Feb", "Mar"}]
frames = {n: xls.parse(n) for n in month_sheets}
print(list(frames))You can also pass an ExcelFile object to read_excel, but calling parse on it is the clearer choice.
Combining sheets into one DataFrame
When sheets hold the same kind of data, such as one sheet per month, you usually want one DataFrame with a column that records where each row came from. Passing the dictionary to pd.concat does this. The dictionary keys become an extra index level, which you can turn into a column.
import pandas as pd
from io import BytesIO
months = pd.read_excel(BytesIO(data), sheet_name=["Jan", "Feb"])
combined = (
pd.concat(months, names=["sheet", "row"])
.reset_index(level="sheet")
.reset_index(drop=True)
)
print(combined)
print(combined.groupby("sheet")["sales"].sum())The result has columns sheet, region and sales, with four rows. The groupby line prints 30 for Jan and 70 for Feb.
concat aligns columns by name. If one sheet spells a column differently, for example Sales instead of sales, you get two separate columns filled with missing values. Check the column names of each sheet before you combine them, or rename them first with frame.rename(columns=str.lower).
Common errors
- Treating a dict as a DataFrame. A list or
Nonereturns a dictionary. Index it by key first, as insheets["Feb"]. - Using a name that is almost right. Compare against
ExcelFile(path).sheet_namesto see the exact spelling, including spaces. - Relying on position. Reordering tabs changes what
sheet_name=1means. - Applying one
usecolsordtypesetting to sheets with different layouts. - Concatenating sheets whose headers differ in spelling or case.
Exercise
A workbook has sheets named "Q1", "Q2", "Q3" and "Summary". You run pd.read_excel(path, sheet_name=["Q1", "Q2"]). What type does the call return, what are its keys, and how would you stack the two quarters into one DataFrame that keeps a column named quarter?
Show answer
It returns a dict of DataFrames with the keys "Q1" and "Q2". Stack them with pd.concat(result, names=["quarter", "row"]).reset_index(level="quarter").reset_index(drop=True). Using names labels the key level as "quarter", and reset_index(level="quarter") turns it into a column.
Exercise
You need the sheet "Data" with only columns "id" and "value", and the sheet "Settings" with all its columns, from a very large workbook. Which approach avoids opening and parsing the file twice, and why can a single read_excel call with a list not do it?
Show answer
Open the file once with pd.ExcelFile(path) and call xls.parse("Data", usecols=["id", "value"]) and xls.parse("Settings"). A single read_excel call with sheet_name=["Data", "Settings"] applies one usecols setting to both sheets, so it would either drop columns from "Settings" or fail if "Settings" lacks "id" or "value".