Sub topic 10
Skipping rows and picking column ranges in Excel
This chapter assumes you can call pd.read_excel on a simple sheet and have an Excel engine such as openpyxl installed. Real workbooks often have a title block above the table, notes beside it, or a totals row below it. The arguments here let you load only the table.
The shape of a messy sheet
Consider a sheet that looks like this:
| Row | A | B | C | D |
|---|---|---|---|---|
| 1 | Quarterly report | |||
| 2 | Prepared by finance | |||
| 3 | region | product | units | note |
| 4-6 | data | data | data | data |
| 7 | Total | 29 |
If you call read_excel with defaults, pandas treats row 1 as the header. You get a column named "Quarterly report" and mostly NaN values. Three arguments fix this.
Skipping rows and limiting rows
skiprows=2 discards the first two sheet rows before pandas looks for the header. The next row, row 3, then becomes the header. nrows=3 reads three data rows after the header, so the totals row is left out.
Picking columns with usecols
usecols accepts an Excel-style string. Letters work as they do in Excel, and ranges include both ends.
import pandas as pd
from io import BytesIO
rows = [
["Quarterly report", None, None, None],
["Prepared by finance", None, None, None],
["region", "product", "units", "note"],
["North", "A", 10, "ok"],
["South", "B", 7, "late"],
["East", "A", 12, "ok"],
["Total", None, 29, None],
]
buffer = BytesIO()
pd.DataFrame(rows).to_excel(buffer, sheet_name="Summary", header=False, index=False)
data = buffer.getvalue()
df = pd.read_excel(
BytesIO(data),
sheet_name="Summary",
skiprows=2,
usecols="A:C",
nrows=3,
)
print(df)
print(df.dtypes)The result has the columns region, product and units, with three rows. The note column and the Total row are gone, and units is read as an integer column.
usecols takes several forms:
"A:C"selects columns A through C."A,C:D"mixes single columns and ranges.[0, 2]selects columns by position, counting from 0 at the left of the sheet.["region", "units"]selects by header name, after the header row is found.- A function such as
lambda name: name != "note"keeps each column for which it returnsTrue.
header versus skiprows
You can reach the same result with header=2. That tells pandas the header is on the third row and drops everything above it. The two arguments differ in what they count:
skiprowsremoves rows first. The header is then the first row that remains.headercounts from the top of the sheet, and the rows above it are discarded.
import pandas as pd
from io import BytesIO
rows = [
["Quarterly report", None, None],
["Prepared by finance", None, None],
["region", "product", "units"],
["North", "A", 10],
["South", "B", 7],
["Total", None, 17],
]
buffer = BytesIO()
pd.DataFrame(rows).to_excel(buffer, header=False, index=False)
data = buffer.getvalue()
a = pd.read_excel(BytesIO(data), header=2, skipfooter=1)
b = pd.read_excel(BytesIO(data), skiprows=2, nrows=2)
print(a.equals(b))This prints True. The example also uses skipfooter=1, which drops the last row of the sheet. It is useful when the number of data rows changes but the totals row is always last.
Common errors
- Letters in lowercase or with spaces. Write
"A:C"or"A,C". A stray space can raise a parsing error. - Treating
A:Cas exclusive. It includes column C, unlike a Python slice. - Mixing name lists and letter ranges. One
usecolsvalue must be all strings of letters, all integers, or all names. Do not combine forms. - Stray merged cells. Merged cells only fill their top-left cell. The other cells read as
NaN, so fill them afterward withffill().
Exercise
A sheet has four title rows, then a header on row 5. The table sits in columns B to D, and the last row of the sheet is a totals row. Write a read_excel call that loads only the table without the totals row.
Show answer
pd.read_excel("file.xlsx", skiprows=4, usecols="B:D", skipfooter=1). Four skipped rows make row 5 the header. "B:D" selects the three columns, and skipfooter=1 drops the totals row. Using header=4 instead of skiprows=4 also works.