How do I read one table out of a file that holds several?

Find where one table starts and ends in a file with notes and two tables, read only that section with skiprows and nrows, and fix its missing values, units and months.

After this lesson, you can read six months of factor returns from a file that also holds notes and a table of annual returns.

Where does the monthly table start and end?

The monthly header is the first line that starts with a comma, line 3, and the table ends at the next blank line, line 10, so it holds 10 − 3 − 1 = 6 data rows. A list comprehension finds both line numbers, so the code still works when a new month or note moves them.

The made-up file holds two notes, six months of factor returns in percent, a blank line, and two years of annual returns, with -99.99 for a missing return. .splitlines() splits the text into lines, enumerate numbers them from 0, and next takes the first blank line after the header. Reading the whole file at once raises a ParserError, because the note on line 0 has one field and the header has five. io.StringIO(text) lets pandas read the text as a file, and a file on disk is read with its name.

Code: the made-up file
text = """Monthly and annual factor returns in percent.
Made-up values for a teaching example. Missing values are -99.99.

,Mkt-RF,SMB,HML,RF
202401,    1.12,   -0.62,    0.83,    0.40
202402,    3.85,    1.47,   -1.56,    0.41
202403,   -0.94,   -2.08,    2.19,    0.40
202404,    2.41,    0.35,  -99.99,    0.42
202405,   -1.73,    0.91,    1.02,    0.41
202406,    0.58,   -1.24,    0.66,    0.40

 Annual Factors: January-December
,Mkt-RF,SMB,HML,RF
2022,  -18.40,   -5.10,   20.30,    1.50
2023,   19.70,   -2.80,  -10.40,    5.00

End of file.
"""

The following box numbers the lines, finds the monthly section and tries to read the whole file.

import io

import pandas as pd

lines = text.splitlines()
for number, line in enumerate(lines):
    print(number, line, sep="|")
header_rows = [number for number, line in enumerate(lines) if line.startswith(",")]
blank_rows = [number for number, line in enumerate(lines) if not line.strip()]
monthly_start = header_rows[0]
monthly_end = next(number for number in blank_rows if number > monthly_start)
print(header_rows, blank_rows, monthly_start, monthly_end)
try:
    pd.read_csv(io.StringIO(text))
except pd.errors.ParserError as error:
    print(type(error).__name__)
0|Monthly and annual factor returns in percent.
1|Made-up values for a teaching example. Missing values are -99.99.
2|
3|,Mkt-RF,SMB,HML,RF
4|202401,    1.12,   -0.62,    0.83,    0.40
5|202402,    3.85,    1.47,   -1.56,    0.41
6|202403,   -0.94,   -2.08,    2.19,    0.40
7|202404,    2.41,    0.35,  -99.99,    0.42
8|202405,   -1.73,    0.91,    1.02,    0.41
9|202406,    0.58,   -1.24,    0.66,    0.40
10|
11| Annual Factors: January-December
12|,Mkt-RF,SMB,HML,RF
13|2022,  -18.40,   -5.10,   20.30,    1.50
14|2023,   19.70,   -2.80,  -10.40,    5.00
15|
16|End of file.
[3, 12] [2, 10, 15] 3 10
ParserError

How do I read only those six rows?

skiprows=monthly_start skips the lines before the header and nrows=monthly_end - monthly_start - 1 reads the six data rows after it, so pd.read_csv returns only the monthly table. na_values=[-99.99] turns April’s marker into NaN, and dividing by 100 turns January’s 1.12% into 0.0112.

index_col=0 uses the first column as row labels, and skipinitialspace=True ignores the spaces after each comma. pd.to_datetime(..., format="%Y%m") reads 202401 as January 2024, and .to_period("M") keeps the month.

The following box reads the monthly table and converts its returns and months.

monthly = pd.read_csv(io.StringIO(text), skiprows=monthly_start, nrows=monthly_end - monthly_start - 1, index_col=0, skipinitialspace=True, na_values=[-99.99]) / 100
monthly.index = pd.to_datetime(monthly.index.astype(str), format="%Y%m").to_period("M")
print(monthly)
         Mkt-RF     SMB     HML      RF
2024-01  0.0112 -0.0062  0.0083  0.0040
2024-02  0.0385  0.0147 -0.0156  0.0041
2024-03 -0.0094 -0.0208  0.0219  0.0040
2024-04  0.0241  0.0035     NaN  0.0042
2024-05 -0.0173  0.0091  0.0102  0.0041
2024-06  0.0058 -0.0124  0.0066  0.0040

Your turn

Read the annual table and print each year’s Mkt-RF return as a decimal. You should see −0.184 for 2022 and 0.197 for 2023.

The annual table starts at the second header.

annual_start = header_rows[1]
annual_end = next(number for number in blank_rows if number > annual_start)
annual = pd.read_csv(io.StringIO(text), skiprows=annual_start, nrows=annual_end - annual_start - 1, index_col=0, skipinitialspace=True)
print((annual["Mkt-RF"] / 100).round(3).to_dict())
{2022: -0.184, 2023: 0.197}