How do you select a row from a Pandas DataFrame or Series by integer position? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you select a row from a Pandas DataFrame or Series by integer position?

message-square
0

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] or df[0] for positional row access (Pandas 2.x/3.0 deprecation & trap):
    • On a Series with integer labels (e.g., after filtering s = s[s != "Lahore"] where index 0 was dropped), s[0] raises KeyError: 0—and in Pandas 2.x/3.x, positional fallback on s[0] is deprecated/removed in favor of label lookup. Always write s.iloc[0] for positional indexing and s.loc[label] for label indexing.
    • On a DataFrame, df[0] looks for a column named 0 (raising KeyError: 0), whereas df[0:1] slices rows positionally—another reason df.iloc[0] / df.iloc[0:1] is far clearer and less error-prone.
  • df.iloc[0] returns a Series, whereas df.iloc[[0]] or df.iloc[0:1] returns a 1-row DataFrame:
    • Single-integer indexing (df.iloc[0]) collapses the row into a 1D Series (and if columns have mixed dtypes like str and float, coerces the Series to object dtype). Pass a list df.iloc[[0]] or slice df.iloc[0:1] when you want to preserve a 2D DataFrame with original column dtypes intact.
  • Exclusive stop index in .iloc[start:stop] vs. inclusive stop in .loc[start:stop]:
    • .iloc[0:2] follows standard Python half-open slicing (returns positions 0 and 1—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 raises IndexError: single positional indexer is out-of-bounds (whereas slice syntax df.iloc[5:10] safely returns an empty DataFrame).

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.