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 ioimport pandas as pdworkbook = 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.
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.