loc vs iloc
Select rows and columns by label (loc) or by integer position (iloc)
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
loc — select by label (row index label, column name): ``python df.loc[0] # row with index label 0 df.loc[0, 'name'] # row 0, column 'name' df.loc[0:2, 'name':'age'] # slice by label (inclusive both ends)
iloc — select by integer position (0-based, like NumPy): ``python df.iloc[0] # first row (position 0) df.iloc[0, 1] # row 0, column at position 1 df.iloc[0:3, 0:2] # first 3 rows, first 2 columns (exclusive end)
Critical difference:
locslices are inclusive at both endsilocslices are exclusive at the end (like Python/NumPy)
# If index is [10, 20, 30, 40]:
df.loc[10:30] # rows with labels 10, 20, 30 (3 rows)
df.iloc[0:3] # rows at positions 0, 1, 2 (3 rows)When to use which:
- Use
locwhen you know the label (column name, named index) - Use
ilocwhen you know the position (first row, last 5 rows)
Examples
loc and iloc side by side
iloc[-2:] selects the last 2 rows regardless of total length
import pandas as pd
df = pd.DataFrame({'name':['Alice','Bob','Carol','Dave'],'age':[25,30,35,28],'salary':[50,65,80,55]})
# First row by position
print(df.iloc[0]) # Alice, 25, 50
# Rows 1-2, columns 'name' and 'age'
print(df.loc[1:2, ['name','age']])
# Last 2 rows
print(df.iloc[-2:])How well did you understand this?
Next in pandas
Filtering Rows