iloc[] is purely positional — selecting position 0 returns the first row regardless of what its actual index label is, selecting column position 1 selects the second column by position, and slicing from position 0 to 2 selects the first two rows, excluding position 2, matching ordinary Python slicing semantics. Since iloc[] ignores labels entirely, it behaves identically whether the DataFrame's index is the default RangeIndex or a custom one, which makes it the right tool when you specifically want positional access independent of whatever labels happen to be in use.
1Understanding df.iloc[]
iloc[] is purely positional — selecting position 0 returns the first row regardless of what its actual index label is, selecting column position 1 selects the second column by position, and slicing from position 0 to 2 selects the first two rows, excluding position 2, matching ordinary Python slicing semantics. Since iloc[] ignores labels entirely, it behaves identically whether the DataFrame's index is the default RangeIndex or a custom one, which makes it the right tool when you specifically want positional access independent of whatever labels happen to be in use.
Use iloc[] when you specifically want positional access that behaves the same regardless of the DataFrame's actual index labels — loc[] instead depends entirely on what those labels are, which changes behavior if the index is reset, reordered, or customized.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob", "Carol"]}, index=["x", "y", "z"])
print(df.iloc[0])2Practical Example
Here is a real-world application of df.iloc[] showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]})
print(df.iloc[1:3, 0])3Best Practices
Follow these guidelines when working with df.iloc[]:
1. Use iloc[] for purely positional access, like getting the first 10 rows, that should work the same regardless of the index's actual labels
2. Use loc[] instead when the selection is naturally based on meaningful labels rather than position
3. Remember iloc[]'s slice endpoint is exclusive, matching ordinary Python slicing, unlike loc[]'s inclusive label-based slicing
Tip: Use iloc[] when you specifically want positional access that behaves the same regardless of the DataFrame's actual index labels — loc[] instead depends entirely on what those labels are, which changes behavior if the index is reset, reordered, or customized.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob", "Carol"]}, index=["x", "y", "z"])
print(df.iloc[0])