How do I read the right table from an Excel workbook?

List the sheets of a workbook, read the table that starts below a block of notes with sheet_name and skiprows, and turn dates written as numbers such as 2024.10 into real dates without losing October.

After this lesson, you can find a monthly table below the notes of an Excel workbook and read its dates correctly.

How do I find the sheet and the table?

pd.ExcelFile(workbook).sheet_names lists the workbook’s sheets, here Notes and Data, and pd.read_excel(workbook, sheet_name="Data", skiprows=7) skips the seven title rows of Data and reads the table below them. October’s index level is 1046.3.

The made-up workbook holds six months of an index’s level in index points and its earnings per index unit, with each month written as year.month, as in Robert Shiller’s workbook. Without sheet_name, pandas reads the first sheet, Notes. pandas reads .xlsx files with openpyxl, installed with python -m pip install openpyxl. Here the workbook lives in memory, and a workbook on disk is read with its file name.

Code: the made-up workbook
import io

import pandas as pd

workbook = io.BytesIO()
with pd.ExcelWriter(workbook) as writer:
    pd.DataFrame({"Notes": ["Monthly index data for a teaching example.", "Dates are written as year.month, so 2024.10 is October 2024."]}).to_excel(writer, sheet_name="Notes", index=False)
    pd.DataFrame({"": ["Index data", "", "Teaching example", "", "", "", ""]}).to_excel(writer, sheet_name="Data", index=False, header=False)
    pd.DataFrame({
        "Date": [2024.07, 2024.08, 2024.09, 2024.10, 2024.11, 2024.12],
        "Price": [1012.4, 1004.8, 1025.1, 1046.3, 1061.9, 1070.2],
        "Earnings": [41.2, 41.5, 41.7, 42.0, 42.4, 42.6],
    }).to_excel(writer, sheet_name="Data", index=False, startrow=7)

The following box lists the sheets and reads the table.

print(pd.ExcelFile(workbook).sheet_names)
index_data = pd.read_excel(workbook, sheet_name="Data", skiprows=7)
print(index_data)
print(index_data.dtypes.to_dict())
['Notes', 'Data']
      Date   Price  Earnings
0  2024.07  1012.4      41.2
1  2024.08  1004.8      41.5
2  2024.09  1025.1      41.7
3  2024.10  1046.3      42.0
4  2024.11  1061.9      42.4
5  2024.12  1070.2      42.6
{'Date': dtype('float64'), 'Price': dtype('float64'), 'Earnings': dtype('float64')}

The Date column holds numbers, float64, so 2024.10 is the same number as 2024.1.

How do I keep October when I convert the dates?

Writing each number with two decimals, "{:.2f}".format, restores the month’s second digit, so pd.to_datetime(..., format="%Y.%m") reads "2024.10" as October. The plain text of the number 2024.10 is "2024.1", which pandas reads as January.

.map() applies the formatting to each number, and format="mixed" lets pandas guess a format for each text. Of the twelve months, only October ends in zero. pandas sets the day to 1.

The following box converts the dates both ways side by side.

plain_text = index_data["Date"].astype(str)
two_decimals = index_data["Date"].map("{:.2f}".format)
print(pd.DataFrame({
    "plain_text": plain_text,
    "plain_month": pd.to_datetime(plain_text, format="mixed").dt.strftime("%Y-%m"),
    "two_decimals": two_decimals,
    "month": pd.to_datetime(two_decimals, format="%Y.%m").dt.strftime("%Y-%m"),
}))
  plain_text plain_month two_decimals    month
0    2024.07     2024-07      2024.07  2024-07
1    2024.08     2024-08      2024.08  2024-08
2    2024.09     2024-09      2024.09  2024-09
3     2024.1     2024-01      2024.10  2024-10
4    2024.11     2024-11      2024.11  2024-11
5    2024.12     2024-12      2024.12  2024-12

Your turn

Give the table the correct months as row labels and print October’s level. You should see 1046.3.

.set_index() takes the parsed dates as labels.

months = pd.to_datetime(two_decimals, format="%Y.%m")
print(index_data.set_index(months).loc["2024-10-01", "Price"])
1046.3