Sub topic 4
Reading only the columns and rows you need
This chapter assumes you can run pd.read_csv on a simple file and know what a DataFrame is. The earlier chapters on first reads, inspection, and separators and headers are the background. Here you will restrict what the parser loads, so wide or long files cost less memory and time and need less cleanup afterward.
Why filter at load time
You could load everything and then write df[["name", "score"]]. That works, but the full table must fit in memory first. If a file has 80 columns and you need 4, or 50 million rows and you need a preview, filtering during the read is cheaper and faster.
Three arguments do most of the work:
| Argument | Selects | Accepts |
|---|---|---|
| `usecols` | Columns | Names, positions, or a function |
| `skiprows` | Lines to ignore | A count, a list of line numbers, or a function |
| `nrows` | How many data rows to read | An integer |
The sample file for this chapter:
import pandas as pd
from io import StringIO
text = """id,name,city,score,notes
1,Ana,Lima,90,a
2,Ben,Oslo,85,b
3,Cy,Rome,70,c
4,Di,Kyiv,60,d
"""Selecting columns with usecols
Pass a list of column names:
df = pd.read_csv(StringIO(text), usecols=["name", "score"])
print(df)The result has two columns, name and score. You can also pass zero-based positions, which helps when a file has no header or messy names:
df = pd.read_csv(StringIO(text), usecols=[0, 3])
print(df.columns.tolist()) # ['id', 'score']Do not mix names and positions in one list. pandas raises a ValueError.
Column order is not preserved
usecols selects columns. It does not reorder them. The result always follows the order in the file:
df = pd.read_csv(StringIO(text), usecols=["score", "name"])
print(df.columns.tolist()) # ['name', 'score']
df = df[["score", "name"]] # reorder explicitly afterward
print(df.columns.tolist()) # ['score', 'name']Selecting with a function
If usecols is a callable, pandas calls it once per column name and keeps the columns for which it returns True. This suits files with many similarly named columns:
df = pd.read_csv(StringIO(text), usecols=lambda c: c in {"id", "city"})
print(df.columns.tolist()) # ['id', 'city']A prefix rule such as lambda c: c.startswith("m_") works the same way.
Misspelled names fail loudly
A name that is not in the file raises an error rather than being ignored:
try:
pd.read_csv(StringIO(text), usecols=["nme"])
except ValueError as err:
print(err)The message lists the columns that were expected but not found. This is useful, because a renamed column in an upstream export stops your pipeline instead of silently dropping data.
What usecols saves
The parser still scans the file, but it does not build arrays for columns you did not select. Memory use drops roughly in proportion to the columns you drop. Parsing time falls less, because every byte is still read. For text-heavy columns you do not need, the saving is large.
Limiting rows with nrows
nrows stops reading after that many data rows. The header line does not count:
df = pd.read_csv(StringIO(text), nrows=2)
print(df["name"].tolist()) # ['Ana', 'Ben']Because the parser stops early, nrows is fast even on huge files. It is a good way to inspect a new file before committing to a full load:
preview = pd.read_csv("big.csv", nrows=1000)
preview.info()Be careful about trusting the dtypes from a preview. A column that looks like integers in the first 1000 rows may contain text later. Use the preview to find column names and plan usecols and dtype, not to prove the types.
Skipping rows with skiprows
skiprows works on file lines, counted from 0. Line 0 is the header line in a normal file.
Skipping a preamble
Exports often begin with report titles before the real header. An integer skips that many lines from the top:
report = "Exported 2024-03-01\nSource: CRM\nid,name\n1,Ana\n2,Ben\n"
df = pd.read_csv(StringIO(report), skiprows=2)
print(df.columns.tolist()) # ['id', 'name']After the two lines are skipped, the next line becomes the header.
Skipping specific lines
A list skips exactly those line numbers:
df = pd.read_csv(StringIO(text), skiprows=[1, 2])
print(df["name"].tolist()) # ['Cy', 'Di']The header at line 0 is kept, and the lines for Ana and Ben (lines 1 and 2) are dropped.
The header off-by-one trap
Compare this with skiprows=2 on the sample file:
df = pd.read_csv(StringIO(text), skiprows=2)
print(df.columns.tolist()) # ['2', 'Ben', 'Oslo', '85', 'b']An integer skips lines from the top, including the real header. The line 2,Ben,Oslo,85,b then becomes the header. When you want to keep the header and drop data rows, pass a list that starts at 1.
Skipping with a function
A callable receives each line number and returns True to skip it. This keeps the header and every other data row:
df = pd.read_csv(StringIO(text), skiprows=lambda i: i > 0 and i % 2 == 0)
print(df["name"].tolist()) # ['Ana', 'Cy']The same idea gives a random sample of a large file. Skip each line with a fixed probability, and always keep line 0:
import random
random.seed(0)
sample = pd.read_csv(
"big.csv",
skiprows=lambda i: i > 0 and random.random() > 0.01,
)This loads about 1% of the rows. The file is still scanned from start to finish, but only the kept rows are stored.
Footers with skipfooter
Some files end with a totals line. skipfooter drops lines from the bottom. It is only supported by the Python parser engine:
footer = "id,amount\n1,10\n2,20\nTotal,30\n"
df = pd.read_csv(StringIO(footer), skipfooter=1, engine="python")
print(df["amount"].sum()) # 30If you leave out engine="python", pandas emits a ParserWarning and falls back anyway. Set it explicitly to keep logs clean. The Python engine is slower, so avoid it on very large files when another option works. Also, skipfooter cannot be combined with nrows.
How the options combine
The filters apply at different stages of the read. This is a conceptual order, not a literal description of the parser's internals:
A combined call for a preview of a wide file looks like this:
df = pd.read_csv(
StringIO(text),
usecols=["id", "name", "score"],
index_col="id",
nrows=3,
dtype={"score": "int32"},
)
print(df)Setting dtype here also saves memory, because int32 uses half the space of the default int64.
usecols and index_col together
When you set index_col by name, include that column in usecols. If you use a position for index_col, count it among the selected columns, not the original file. Names avoid this ambiguity, so prefer them.
Common mistakes
- Expecting
usecols=["b", "a"]to returnbfirst. The file order wins. - Using
skiprows=1to skip the first data row. It skips the header instead. - Forgetting that
nrowscounts data rows, not file lines. - Trusting dtypes inferred from a short
nrowspreview. - Using
skipfooterwithoutengine="python".
read_excel accepts usecols, skiprows and nrows too, with an Excel-style range string such as "A:C" for columns. A later chapter covers those.
Exercise
A file has two title lines, then a header, then 1,000,000 data rows with columns id, region, sales and comments. You want only region and sales for the first 500 data rows, and you want region listed first in the result. Write the read_csv call and any step needed to get the order right.
Show answer
Use df = pd.read_csv("data.csv", skiprows=2, usecols=["region", "sales"], nrows=500). Because usecols does not reorder, the result follows the file order, so if sales comes before region in the file, finish with df = df[["region", "sales"]]. The integer skiprows=2 removes the two title lines, so the next line is the header, and nrows=500 counts data rows only.
Exercise
What is the difference between skiprows=1 and skiprows=[1] on a normal CSV file with a header?
Show answer
skiprows=1 skips the line at position 0, which is the header, so the first data row becomes the header. skiprows=[1] skips only the line at position 1, the first data row, and keeps the header at line 0.