Sub topic 5
Selecting Rows and Columns with .iloc
This chapter assumes you can build a DataFrame from a dictionary and that you know the .loc basics from the previous chapter. It also assumes you know how Python slices work.
The working model
.iloc selects by integer position. Positions start at 0 and run along the rows and columns in their current order. The index labels ("a" to "e") play no part. The call has the form df.iloc[row_selector, column_selector]. The column selector is optional.
Slices follow Python list rules. The start is included and the stop is excluded. This is the opposite of .loc, which includes both slice endpoints.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Cairo", "Quito"],
"country": ["Norway", "Peru", "India", "Egypt", "Ecuador"],
"population_k": [709, 10092, 3124, 10230, 2800],
"continent": ["Europe", "South America", "Asia", "Africa", "South America"],
},
index=["a", "b", "c", "d", "e"],
)
print(df.iloc[0]) # first row, returned as a Series
print(df.iloc[[0, 2]]) # rows at positions 0 and 2, as a DataFrame
print(df.iloc[1:3, [0, 2]]) # rows b and c, columns city and population_k
print(df.iloc[-2:]) # last two rows
print(df.iloc[:, 1:3]) # all rows, columns country and population_k
print(df.iloc[::2]) # every second row: a, c, e
print(df.iloc[1, 2]) # one value: 10092What each selector returns
The type of selector decides the shape of the result.
| Selector | Example | Result |
|---|---|---|
| Single integer | `df.iloc[0]` | Series for that row |
| Two integers | `df.iloc[1, 2]` | Single value |
| List of integers | `df.iloc[[0, 2]]` | DataFrame |
| Slice | `df.iloc[1:3]` | DataFrame |
| Boolean array | `df.iloc[mask_array]` | DataFrame |
A list always keeps the dimension, so df.iloc[[0]] returns a one-row DataFrame, not a Series.
Common errors
An out-of-range integer raises an error, but an out-of-range slice does not. df.iloc[10] raises IndexError. df.iloc[3:10] quietly returns the last two rows. This matches Python lists.
A boolean Series is rejected. .iloc accepts boolean arrays but not a boolean Series, because a Series carries an index and .iloc ignores labels. Convert the mask first.
mask = df["population_k"] > 3000
print(df.iloc[mask.to_numpy()]) # works
# df.iloc[mask] raises ValueErrorIn practice, use df[mask] or df.loc[mask] for boolean filtering. They accept the Series directly.
Positions are fragile. After you sort or filter, the row at position 0 is a different row. Code such as df.iloc[0] silently changes meaning when an earlier step changes the order. Use .iloc when the position is the point, for example "the first row" or "the last three rows". Use .loc when you mean a specific label.
Integer labels hide the difference. If the index is [10, 20, 30], then df.iloc[0] is the row labeled 10. df.loc[0] raises KeyError. Check which one you mean.
Assigning with .iloc
.iloc also works on the left side of an assignment. This writes into the original DataFrame.
df.iloc[0, 2] = 710
print(df.iloc[0, 2]) # 710Use a single .iloc call with both selectors. Chaining two selections, such as df.iloc[0:2]["population_k"] = 0, can write to a temporary copy. That is the chained-indexing problem covered in a later chapter.
Exercise
Using the DataFrame above, write one .iloc expression that returns the country and continent of the last two rows. Then say how the result differs from df.iloc[-2:, [1, 3]] if you wrote df.iloc[-2, [1, 3]] instead.
Show answer
Use df.iloc[-2:, [1, 3]]. The slice -2: selects the last two rows, and [1, 3] selects the country and continent columns by position. With df.iloc[-2, [1, 3]], the single integer -2 selects only the second-to-last row, so the result is a Series, not a two-row DataFrame.