Rows & Subsets: loc / iloc
🎬 Watch the 6:12 video of this topic ↓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.
Grab a rectangle of the DataFrame by rows AND columns. .loc uses labels and INCLUDES the end; .iloc uses positions and EXCLUDES it.
Name | English | IP | Maths | |
|---|---|---|---|---|
ID 1 | Rinku | 65 | 89 | 72 |
ID 2 | Ritu | 77 | 83 | 69 |
ID 3 | Pankaj | 72 | 95 | 87 |
ID 4 | Ajay | 81 | 99 | 94 |
ID 5 | Aditya | 92 | 87 | 96 |
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:
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:
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.
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.
.loc = labels, end included. .iloc = positions, end excluded. Both take [rows, columns]. For a single cell use .at (labels) or .iat (positions).df has rows ID 1–ID 5. What does df.loc['ID 2':'ID 4'] return?
What does df.iloc[1:3] return (positions)?
DataFrame: loc, iloc, at, iat, in 6:12
One animated video of this topic, narrated. Watch it before the lessons for the big picture, or after them to revise.
🔊 Hindi mein sunna hai? Watch on YouTube with Hindi audio ↗(there, choose ⚙ Settings → Audio track → Hindi)