LambdaLab
Informatics Practices · Class 12 · Python Pandas · DataFrame
PandasDataFrame⏱️ 11 min read

Rows & Subsets: loc / iloc

Selecting columns was easy. To pull out rows — or a rectangle of rows and columns — you use .loc and .iloc, exactly like a Series but now with two directions.

1Grab a rectangle

The syntax is df.loc[rows, columns]. Drag the pickers to select a subset and watch the golden rule in action: .loc keeps the end, .iloc drops it.

loc / iloc subset explorer

Grab a rectangle of the DataFrame by rows AND columns. .loc uses labels and INCLUDES the end; .iloc uses positions and EXCLUDES it.

df.loc['ID 1':'ID 4', 'Name':'IP']
Name
English
IP
Maths
ID 1
Rinku658972
ID 2
Ritu778369
ID 3
Pankaj729587
ID 4
Ajay819994
ID 5
Aditya928796
Selected 4 rows × 3 columns.
End labels are INCLUDED ✓

2.loc — by label, inclusive

.loc uses the row and column labels, and both the start and end labels are included. Use :on either side to mean "all".

You can also select rows and columns discretely (specific, non-adjacent items) by passing a list of labels instead of a slice:

df_loc.py

3.iloc — by position, exclusive

.iloc uses integer positions (starting at 0), and the end position is excluded — just like list slicing.

Just like with .loc, you can select specific rows and columnsdiscretely by passing a list of integer positions:

df_iloc.py

4.loc with conditions

A superpower of .loc (that .iloc doesn't have): you can pass a condition for the rows and even list the columns you want in the same call.

df_loc_cond.py

5A single value: at & iat

To read one cell, the fastest tools are .at (by labels) and .iat (by positions) — the DataFrame twins of the Series .at/.iat.

df_at_iat.py
Key Takeaway
.loc = labels, end included. .iloc = positions, end excluded. Both take [rows, columns]. For a single cell use .at (labels) or .iat (positions).
Quick Check

df has rows ID 1–ID 5. What does df.loc['ID 2':'ID 4'] return?

Quick Check

What does df.iloc[1:3] return (positions)?