← Data analysis with Python

loc and iloc

Pick rows and columns together, by label or by position.

Start this lesson

Two tools select rows and columns at the same time. df.loc[rows, columns] works with labels: row index labels or masks, and column names. df.iloc[rows, columns] works with positions: 0 for the first row, 1 for the second, and so on, just like list slicing. A useful trick is set_index: make a column like "month" the row labels, and then weather.loc["Jul", "high"] reads one cell by name.

import io
import pandas as pd

csv_text = """month,high,low,rain_mm
Jan,8,1,78
Feb,10,2,60
Mar,14,5,55
Apr,18,8,42
May,23,12,35
Jun,28,17,20
Jul,31,20,12
Aug,30,19,15
Sep,26,15,30
Oct,20,10,58
Nov,13,5,72
Dec,9,2,85
"""
weather = pd.read_csv(io.StringIO(csv_text))
print(weather.iloc[0:3])                 # first three rows
print(weather.loc[weather["high"] > 28, ["month", "high"]])

by_month = weather.set_index("month")
print(by_month.loc["Jul", "high"])

iloc[0:3] gives rows 0, 1, 2 (the end is not included, like list slicing). The loc line filters rows and chooses columns in one step. After set_index, "Jul" is a row label, so loc can find July’s high, 31.

One difference: iloc[0:3] stops before 3, but loc with labels includes both ends.

iloc[-1] is the last row, just as with lists.