iloc[]
iloc selects rows and columns by integer position, ignoring labels.
In this page:
Syntax
df.iloc[row_positions, column_positions]
df.iloc[0:3, 0:2]
iloc[]
df.iloc[row_positions, column_positions] works like NumPy indexing, starting at 0 and excluding the end of a slice. It accepts integers, lists and slices, but not label-based masks of Series.
Use it when you care about position, such as the first or last rows.
Note:
df.iloc[-1] returns the last row.
Example: iloc[]
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]})
print(df.iloc[0])
print(df.iloc[1:, :2])
print(df.iloc[-1, 2])
# Output:
# a 1
# b 4
# c 7
# Name: 0, dtype: int64
# a b
# 1 2 5
# 2 3 6
# 9
Related Topics
Common Mistakes
- Passing labels to iloc
- Expecting inclusive slices
- Using a boolean Series instead of a plain boolean array
Chapter Summary
- iloc is position-based
- Slices exclude the end
- Negative positions work
- Accepts integers, lists and slices
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: