Sub topic 4
Reading only the columns and rows you need
This chapter assumes you can run Python, have pandas installed, and know what a DataFrame is. You should also have used read_csv with its default settings. Here you will limit what pandas loads, which saves memory and time before any cleaning starts.
Why filter while reading
By default, read_csv parses every column and every row. A wide file with 80 columns costs memory for all 80, even if your analysis needs three. Selecting at load time means pandas never builds the columns you skip. That is cheaper than loading everything and then dropping columns.
Choosing columns with usecols
Pass a list of column names to usecols. Pandas parses only those columns.
import pandas as pd
from io import StringIO
text = "zip,city,notes\n02134,Boston,a\n10001,New York,b\n"
df = pd.read_csv(
StringIO(text),
usecols=["zip", "city"],
dtype={"zip": "string"},
)
print(df["zip"].tolist())
print(df.columns.tolist())The output is ['02134', '10001'] and then ['zip', 'city']. The dtype argument keeps the leading zero in 02134. Without it, pandas infers an integer and the zero is lost. Data types get a full chapter later.
You can also pass positions, such as usecols=[0, 1]. Names are safer, because they survive a change in column order.
Column order is not preserved
The order of names in usecols does not change the order of the result. Columns come back in file order. To reorder them, index the result afterwards.
import pandas as pd
from io import StringIO
text = "a,b,c\n1,2,3\n4,5,6\n"
df = pd.read_csv(StringIO(text), usecols=["c", "a"])
print(df.columns.tolist())
df = df[["c", "a"]]
print(df.columns.tolist())The first print shows ['a', 'c']. The second shows ['c', 'a'].
Selecting with a function
usecols also accepts a callable. Pandas calls it with each column name, and it keeps the columns where the function returns True.
import pandas as pd
from io import StringIO
text = "id,temp_min,temp_max,station\n1,3,9,A\n2,1,7,B\n"
df = pd.read_csv(StringIO(text), usecols=lambda name: name.startswith("temp"))
print(df.columns.tolist())This prints ['temp_min', 'temp_max'].
Limiting rows
Three arguments control which rows are read.
| Argument | What it does |
|---|---|
| `nrows` | Reads only the first N data rows, then stops. |
| `skiprows` | Skips rows at the start of the file, or rows picked by a list or function. |
| `skipfooter` | Skips rows at the end. It needs `engine="python"`. |
nrows is useful for a quick look at a very large file.
import pandas as pd
from io import StringIO
text = "id,value\n1,10\n2,20\n3,30\n4,40\n"
preview = pd.read_csv(StringIO(text), nrows=2)
print(preview)
later = pd.read_csv(StringIO(text), skiprows=[1, 2])
print(later)The first frame holds ids 1 and 2. In the second call, skiprows=[1, 2] skips file lines 1 and 2, which are the first two data lines. Line 0 is the header, so it stays, and the frame holds ids 3 and 4.
Combining both
The two kinds of filtering work together. This pattern is common when you explore a new file.
import pandas as pd
from io import StringIO
text = "id,name,score\n1,Ana,90\n2,Ben,85\n3,Cy,70\n"
sample = pd.read_csv(StringIO(text), usecols=["id", "score"], nrows=2)
print(sample)Where this leads
Column selection is the first step in reading large files. In a later chapter you will combine usecols with chunksize to process files that do not fit in memory.
Exercise
A CSV has columns id, region, amount and comment. Write a read_csv call that loads only id and amount from the first 100 data rows. What order will the columns have if you write usecols=["amount", "id"]?
Show answer
Use pd.read_csv("file.csv", usecols=["id", "amount"], nrows=100). The columns come back in file order, id then amount, even if usecols lists amount first. To change the order, index the result with df[["amount", "id"]].