Sub topic 10
Skipping rows and picking column ranges in Excel
Spreadsheets made for people rarely start at cell A1 with a clean header row. They have a title, a "generated on" line, blank spacer rows, a notes column, and a totals row at the bottom. This chapter shows how to tell pandas.read_excel which part of a sheet is the table, so you get a clean DataFrame without cleaning it afterward.
This chapter assumes you can call read_excel on a file and read one sheet. It also assumes openpyxl is installed (pip install openpyxl) and that you know how DataFrame columns and dtypes work.
A sheet with clutter around the table
The examples build a small workbook in memory, so you can run them without an Excel file. Its layout looks like this:
| Row | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| 1 | Quarterly report | |||||
| 2 | Generated 2024-04-01 | |||||
| 3 | (blank) | |||||
| 4 | Region | Q1 | Q2 | Comment | (blank) | Internal |
| 5 | North | 10 | 12 | ok | 9001 | |
| 6 | South | 8 | 7 | late | 9002 | |
| 7 | East | 15 | 18 | 9003 | ||
| 8 | Total | 33 | 37 |
The real table is A4:C7. Rows 1 to 3 are decoration, column D holds free text, column F is an internal key you do not need, and row 8 is a total that would distort any sum you compute later.
import pandas as pd
from io import BytesIO
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "Summary"
rows = [
["Quarterly report"],
["Generated 2024-04-01"],
[None],
["Region", "Q1", "Q2", "Comment", None, "Internal"],
["North", 10, 12, "ok", None, 9001],
["South", 8, 7, "late", None, 9002],
["East", 15, 18, None, None, 9003],
["Total", 33, 37],
]
for row in rows:
ws.append(row)
buffer = BytesIO()
wb.save(buffer)
buffer.seek(0)
df = pd.read_excel(buffer, skiprows=3, usecols="A:C", nrows=3)
print(df)Output:
Region Q1 Q2
0 North 10 12
1 South 8 7
2 East 15 18Three arguments did the work. skiprows=3 discarded the first three sheet rows. usecols="A:C" kept three columns. nrows=3 stopped after three data rows, which left out the total.
How the arguments combine
read_excel applies the arguments in a fixed order, and most confusion comes from getting that order wrong.
The consequence is that header counts rows after skiprows has removed its rows. With skiprows=3, the default header=0 means "the first row that remains", which is sheet row 4. If you leave skiprows out and pass header=3, you get the same DataFrame, because header also discards the rows above it. Choose whichever reads more clearly, but do not combine them without checking the result. skiprows=3, header=3 would look for the header three rows below row 4.
Skipping rows
The skiprows argument accepts three forms.
| Form | Meaning | Example |
|---|---|---|
| Integer | Skip that many rows from the top | `skiprows=3` |
| List of integers | Skip exactly those rows, numbered from 0 | `skiprows=[0, 1, 2]` |
| Callable | Called with each row number, return `True` to skip | `skiprows=lambda i: i < 3` |
The list and callable forms matter when the junk is not all at the top. For example, a report might repeat a "Page 2" banner row every 50 lines. skiprows=lambda i: i < 3 or i % 51 == 0 handles that case, though you should confirm the row numbers against your own file.
Row numbers are 0-based, so sheet row 1 is row number 0. This is a common source of off-by-one errors when you read row numbers from Excel's own interface.
Skipping the bottom
Use skipfooter to drop rows from the end. It is more robust than nrows when the number of data rows changes between files, since the totals row is always last.
buffer.seek(0)
df = pd.read_excel(buffer, skiprows=3, usecols="A:C", skipfooter=1)
print(df)This prints the same three rows as before. Use nrows when you know how many data rows to read and want to stop early, which also saves time on large sheets. Use skipfooter when the footer has a fixed size and the body does not.
Files with no header
Some sheets have no header row at all. Pass header=None so pandas does not consume the first data row as column names, and supply your own with names.
buffer.seek(0)
df = pd.read_excel(
buffer,
skiprows=4,
header=None,
usecols="A:C",
names=["region", "q1", "q2"],
nrows=3,
)
print(df)Here skiprows=4 also skips the real header at row 4, so the first row read is the North row. The names list must have the same length as the number of columns kept by usecols.
Picking columns with usecols
The usecols argument has four forms. The first one is specific to Excel.
- Excel-style letters. A string such as
"A:C"selects columns by their spreadsheet letters. Both ends are included, unlike a Python slice. You can mix ranges and single letters with commas:"A,C:D"or"A:C,F". - Integer positions.
usecols=[0, 1, 2, 5]selects columns by 0-based position in the sheet. - Header names.
usecols=["Region", "Q2"]selects columns by the text in the header row. - A callable. The function receives each column name and returns
Trueto keep it.
buffer.seek(0)
by_letter = pd.read_excel(buffer, skiprows=3, usecols="A:C,F", nrows=3)
print(list(by_letter.columns))
buffer.seek(0)
by_name = pd.read_excel(buffer, skiprows=3, usecols=["Region", "Q2"], nrows=3)
print(list(by_name.columns))
buffer.seek(0)
by_rule = pd.read_excel(
buffer, skiprows=3, usecols=lambda name: name != "Comment", nrows=3
)
print(list(by_rule.columns))Output:
['Region', 'Q1', 'Q2', 'Internal']
['Region', 'Q2']
['Region', 'Q1', 'Q2', 'Internal']The third call keeps column E, but it has no header text, so pandas names it Unnamed: 4 while reading. It is then dropped because the table has no values there. If your callable keeps unnamed columns, you will see Unnamed: N columns in the result, where N is the 0-based position.
Choosing between the forms
Letters and positions break when someone inserts a column in the workbook. Names break when someone renames a header. Pick the one that matches how your files tend to change. Names are usually the safest for files that are edited by hand. Letters are the best fit for fixed templates where the layout is a contract, since they map directly to what a person sees in Excel.
The forms cannot be mixed in one list. usecols=["Region", 2] raises a ValueError.
Common errors
- Skipping one row too many or too few. If the header comes out as a data row, such as
Northand10, you skipped one row too many. If it comes out asUnnamed: 0or a title, you skipped too few. Printdf.head()and compare it with the sheet. - Numbers read as text. If a totals row or note remains inside the table range, a numeric column becomes
object. Checkdf.dtypesafter loading. - Wrong column count with
names. Anameslist longer than the selected columns raises an error. A shorter one makes pandas use the leftover leading columns as the index, which silently changes the shape. - Merged header cells. Excel stores a merged cell's value only in its top-left cell. The other cells read as empty, so you get
Unnamedcolumns. Fix this by skipping to the lower header row and supplyingnames. - Hidden rows and columns. These are still read. Hiding a row in Excel does not exclude it from the DataFrame.
Putting it together
A reusable loader keeps the layout rules in one place and checks that the result looks right.
def load_summary(source):
df = pd.read_excel(
source,
sheet_name="Summary",
skiprows=3,
usecols="A:C",
skipfooter=1,
)
expected = ["Region", "Q1", "Q2"]
if list(df.columns) != expected:
raise ValueError(f"Unexpected columns: {list(df.columns)}")
return df
buffer.seek(0)
print(load_summary(buffer).dtypes)The column check catches the case where someone adds a title row and shifts the header. Without it, the loader would read the wrong header and fail later with a less helpful error.
Exercise
Using the workbook built in this chapter, write one read_excel call that returns only the columns Region and Internal, only for the data rows (no total row), and with the header taken from sheet row 4. Which arguments do you pass?
Show answer
pd.read_excel(buffer, skiprows=3, usecols="A,F", nrows=3) works, as does usecols=["Region", "Internal"]. Using skipfooter=1 in place of nrows=3 also removes the total row. Remember to call buffer.seek(0) first. skiprows=3 removes sheet rows 1 to 3, so row 4 becomes the header.
Exercise
A sheet has a title in row 1, the header in row 2, and data from row 3. A colleague writes pd.read_excel(path, skiprows=1, header=1). What does the DataFrame contain, and how do you fix the call?
Show answer
skiprows=1 removes row 1, so the header would be at the first remaining row. header=1 then looks one row further down, so row 3 (the first data row) is used as the column names and the real header row is lost. Fix it by using either skiprows=1 alone or header=1 alone.