Skip to the workspace
Pebellslearn by building
pandas Series and DataFrames  ›  Lesson

Selecting with loc and iloc

Indexing & Slicing 14 minloc selects rows and columns by their labels and includes the end of a slice, while iloc selects by integer position and excludes it.

python data analysis / Selecting with loc and iloc

Explore each scene at your own pace.

01 · The rule

The rule

Selecting with loc and iloc

"What was the branch on sale 4?" "Show rows 2 to 4, just branch and copies." A DataFrame has two ways to point at cells: by the labels printed on it, or by counting positions. pandas gives each its own tool, and mixing them up is the most common beginner bug in pandas.

The rule

loc uses labels and includes the end; iloc uses positions and excludes it.

We keep using sales, now with its revenue column (8 rows; columns date, branch, genre, copies, price, revenue).

sales.loc[4, "branch"]              # 'Delhi'   row label 4, column named branch
sales.loc[2:4, ["branch", "copies"]]  # rows labelled 2, 3 AND 4

sales.iloc[4, 1]                    # 'Delhi'   5th row, 2nd column
sales.iloc[2:4, [1, 3]]             # rows at positions 2 and 3 only

Both take [rows, columns], and both accept a single item, a list, or a slice in each part. A colon alone means "all": sales.loc[:, "price"] is the whole price column.

So far labels and positions look identical, because the default index is 0, 1, 2… The difference becomes obvious once the index is something else:

by_date = sales.set_index("date")
by_date.loc["2024-03-02"]     # both rows with that date label
by_date.iloc[0]               # the first row, whatever its label

loc also takes a boolean mask for the rows, which is how the next lesson filters data:

sales.loc[sales["copies"] > 4, "branch"]   # Delhi, Chennai
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.