Use .iloc[pos] (df.iloc[0] or s.iloc[0] for a single row by zero-based integer position, or df.iloc[[0, 2]] / df.iloc[0:3] for multiple rows) to select rows strictly by physical offset regardless of whether the DataFrame or Series index uses custom strings, dates, or non-contiguous integer labels.
Basic Example
import pandas as pd
df = pd.DataFrame(
{"city": ["Lahore", "Karachi", "Islamabad"], "pop_m": [13.5, 17.2, 1.2]},
index=["row_a", "row_b", "row_c"], # Non-integer index labels
)
s = df["city"]
# 1. Recommended: Select single row by zero-based integer position (returns a Series / scalar)
first_row = df.iloc[0]
print(first_row["city"]) # Output: Lahore
print(s.iloc[-1]) # Output: Islamabad (negative indexing works just like Python lists)
# 2. Select multiple rows by integer position (returns a DataFrame / Series):
subset_df = df.iloc[[0, 2]] # 1st and 3rd rows
slice_df = df.iloc[0:2] # 1st and 2nd rows (stop index 2 is EXCLUSIVE!)
print(subset_df)
# city pop_m
# row_a Lahore 13.5
# row_c Islamabad 1.2
Key Details & Edge Cases
- Never use
s[0]ordf[0]for positional row access (Pandas 2.x/3.0 deprecation & trap):- On a
Serieswith integer labels (e.g., after filterings = s[s != "Lahore"]where index0was dropped),s[0]raisesKeyError: 0—and in Pandas 2.x/3.x, positional fallback ons[0]is deprecated/removed in favor of label lookup. Always writes.iloc[0]for positional indexing ands.loc[label]for label indexing. - On a
DataFrame,df[0]looks for a column named0(raisingKeyError: 0), whereasdf[0:1]slices rows positionally—another reasondf.iloc[0]/df.iloc[0:1]is far clearer and less error-prone.
- On a
df.iloc[0]returns aSeries, whereasdf.iloc[[0]]ordf.iloc[0:1]returns a 1-rowDataFrame:- Single-integer indexing (
df.iloc[0]) collapses the row into a 1DSeries(and if columns have mixed dtypes likestrandfloat, coerces the Series toobjectdtype). Pass a listdf.iloc[[0]]or slicedf.iloc[0:1]when you want to preserve a 2DDataFramewith original column dtypes intact.
- Single-integer indexing (
- Exclusive stop index in
.iloc[start:stop]vs. inclusive stop in.loc[start:stop]:.iloc[0:2]follows standard Python half-open slicing (returns positions0and1—2 rows total), whereas.loc["row_a":"row_b"]is inclusive of the end label.
- Out-of-bounds integer position raises
IndexError:- Calling
df.iloc[5]on a 3-row DataFrame raisesIndexError: single positional indexer is out-of-bounds(whereas slice syntaxdf.iloc[5:10]safely returns an empty DataFrame).
- Calling
Comparison of Row-Selection Indexers in Pandas
| Indexer | Lookup Basis | Single-Row Return Type (df) |
Slice End Behavior (a:b) |
Best Used When |
|---|---|---|---|---|
df.iloc[pos] / s.iloc[pos] (Recommended) |
Zero-based integer position (0, -1) |
pd.Series (for df) / scalar (for s) |
Exclusive (b excluded) |
Selecting the first, last, or $n$-th physical row regardless of index labels. |
df.iloc[[pos]] / df.iloc[pos:pos+1] |
Zero-based integer position | 1-row pd.DataFrame |
Exclusive (b excluded) |
Keeping the result as a 2D DataFrame with original column dtypes preserved. |
df.loc[label] / s.loc[label] |
Exact index label ("row_a", date, ID) |
pd.Series / scalar |
Inclusive (b included) |
Looking up rows by meaningful index keys rather than row offset. |
df.head(1) / df.tail(1) |
First / last $n$ physical rows | 1-row pd.DataFrame |
N/A | Safely grabbing the top or bottom rows without raising IndexError if empty. |
You must log in or register to comment.
