Sub topic 8
Reading an Excel File
This chapter assumes you can run Python scripts, install packages with pip, and know what a DataFrame is. You should also have used read_csv, because read_excel takes many of the same arguments.
What read_excel does
pandas.read_excel loads one sheet of a workbook into a DataFrame. A workbook is the whole Excel file, and a sheet is one tab inside it. By default pandas reads the first sheet, treats the first row as column names, and builds a fresh integer index.
Unlike CSV, an Excel file is a zipped bundle of XML files. pandas cannot parse that itself, so it hands the work to a separate library called an engine. For .xlsx files the usual engine is openpyxl, which you install yourself.
pip install pandas openpyxlA first example
The next script builds a small workbook in memory and then reads it back. This keeps the example self-contained, with no file to download.
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)The script does three things:
ExcelWriterwrites two sheets, namedJanandFeb, into the buffer.buffer.seek(0)rewinds the buffer so the reader starts at the beginning.ExcelFileopens the workbook once.sheet_nameslists the tabs, andparse("Feb")loads one of them.
The output is ['Jan', 'Feb'], followed by a DataFrame with a sales column holding 3 and 4.
read_excel and ExcelFile
For one sheet from a file on disk, call read_excel directly:
import pandas as pd
df = pd.read_excel("report.xlsx")When you need several sheets, or want to look at the sheet names first, use ExcelFile. It opens the file once and lets you call parse as many times as you like. Each call to read_excel on a path opens and decodes the file again, so repeated calls are slower.
The diagram below shows the flow from file to DataFrame.
Arguments you already know
Many read_csv options work the same way in read_excel:
| Argument | Effect |
|---|---|
| `header` | Row to use for column names |
| `names` | Your own column names |
| `index_col` | Column to use as the index |
| `usecols` | Columns to keep |
| `dtype` | Data type per column |
| `na_values` | Extra strings to treat as missing |
| `nrows` | Number of rows to read |
Excel adds sheet_name, which picks the tab. The next chapter covers it in detail.
Common errors
Other problems you may meet:
FileNotFoundError: the path is relative to the directory where you run Python, not to the script file.ValueError: Worksheet named 'X' not found: the name is misspelled or has different capitalization. CheckExcelFile(...).sheet_names.- Dates that come back as numbers: the cell was stored as a plain number. Convert it after loading, or fix the format in the source file.
- Formulas: pandas reads the last value Excel saved for a formula cell, not the formula text.
Exercise
Why would you open a workbook with pd.ExcelFile instead of calling pd.read_excel three times to load three sheets?
Show answer
ExcelFile opens and decodes the file once, and you then call parse for each sheet. Three read_excel calls on a path would open and decode the file three times. ExcelFile also gives you sheet_names so you can see which sheets exist before you load them.