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 difference between a label and a position from the previous chapter. It also assumes you have read the chapter on .loc, because .iloc is easiest to learn by comparing the two.
What .iloc does
.iloc selects rows and columns by integer position. The "i" stands for integer. Positions start at 0 and ignore the index labels completely. The first row is position 0 whether its label is "a", 2019, or "Oslo".
The general form is df.iloc[row_selector, column_selector]. If you give only one selector, it applies to rows and all columns are kept.
The examples in this chapter use the DataFrame below. Later blocks reuse df, so run this one first.
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])
print(df.iloc[1, 2])The first print shows row a as a Series, with the column names as its index:
city Oslo
country Norway
population_k 709
continent Europe
Name: a, dtype: objectThe second prints 10092, the value in row position 1 (Lima) and column position 2 (population_k).
Accepted selectors
Each of the two positions in .iloc[rows, columns] accepts the same kinds of input.
| Selector | Example | Result |
|---|---|---|
| Integer | `df.iloc[2]` | One row as a Series |
| List of integers | `df.iloc[[0, 3]]` | A DataFrame, in the order you list |
| Slice | `df.iloc[1:4]` | A DataFrame, end excluded |
| Boolean array | `df.iloc[[True, False, True, False, False]]` | Rows where the value is True |
| Callable | `df.iloc[lambda d: [0, 1]]` | Whatever the function returns, using one of the forms above |
The callable form receives the DataFrame and returns one of the other forms. It is most useful in method chains, where you do not have a name for the intermediate result.
Integers return a Series, lists return a DataFrame
A single integer removes a dimension. A list or slice keeps it. This matches the rule for column brackets: df["city"] gives a Series and df[["city"]] gives a DataFrame.
print(type(df.iloc[0])) # Series: one row
print(type(df.iloc[[0]])) # DataFrame: one row, still two-dimensional
print(type(df.iloc[:, 0])) # Series: one column
print(type(df.iloc[:, [0]])) # DataFrame: one column
print(type(df.iloc[0, 0])) # a plain scalar (str here)When later code expects a DataFrame, wrap the position in a list.
Slices exclude the end
Slices in .iloc follow ordinary Python rules. The start is included and the stop is excluded. This is the opposite of .loc, where label slices include the end.
print(df.iloc[1:3, [0, 2]]) city population_k
b Lima 10092
c Pune 3124Rows at positions 1 and 2 are returned (b and c). Position 3 (d) is not. The equivalent .loc call would be df.loc["b":"c", ["city", "population_k"]], with the end label written as "c", not "d".
Negative positions and steps
Negative integers count from the end, and slices accept a step, as in a list.
print(df.iloc[-2:]) # last two rows: d and e
print(df.iloc[::2]) # every second row: a, c, e
print(df.iloc[[0, -1], :2]) # first and last row, first two columnsThe last line returns:
city country
a Oslo Norway
e Quito EcuadorUsing -1 is the usual way to get the last row without knowing how many rows there are.
Out-of-bounds behavior
Slices and lists behave differently when a position does not exist.
- A slice that runs past the end is clipped silently.
df.iloc[3:100]returns rowsdande. - A single integer or a list containing a position that does not exist raises
IndexError. Bothdf.iloc[10]anddf.iloc[:, [0, 9]]fail.
print(df.iloc[3:100]) # works: rows d and e
try:
df.iloc[10]
except IndexError as err:
print("IndexError:", err)A slice that runs past the end can hide an off-by-one mistake. If your code must fail on bad positions, check len(df) or use a list.
Boolean arrays, but not boolean Series
.iloc accepts a boolean array, but it rejects a boolean Series. A Series carries its own index, and .iloc refuses to guess whether to align by label or by position. Pandas raises a ValueError in this case.
mask = df["population_k"] > 3000
# df.iloc[mask] # ValueError: Series mask is not allowed
print(df.iloc[mask.to_numpy()]) # works: a plain NumPy boolean array
print(df.loc[mask]) # the usual way: .loc accepts the SeriesFor ordinary filtering, use .loc[mask] or df[mask], which align by label. Use .iloc with to_numpy() only when you already have a positional array, for example from NumPy code.
Positions are not stable
Position 0 means the first row in the DataFrame as it is now. After sorting, filtering, or dropping rows, the same row can sit at a different position.
ranked = df.sort_values("population_k", ascending=False)
print(ranked.iloc[0]["city"]) # Cairo: the largest population
print(df.iloc[0]["city"]) # Oslo: the first row in the original order
print(ranked.iloc[:3]) # the three largest citiesranked.iloc[:3] is a correct "top three" only because the sort comes immediately before it. Code that stores a position and uses it later, after the data may have changed, is fragile. When the row has a meaningful identity, such as a city or an ID, prefer a label with .loc.
Mixing positions and labels
Sometimes you know the row position but want to name the columns, or the reverse. .iloc takes only integers, so convert one side.
# Rows by position, columns by label
rows = df.index[1:3]
print(df.loc[rows, ["city", "population_k"]])
# Columns by label, converted to a position
col = df.columns.get_loc("population_k")
print(df.iloc[:2, col])df.index[1:3] slices the index by position and returns labels, which .loc then uses. df.columns.get_loc("population_k") returns the integer position, here 2. Naming columns this way keeps the code correct if someone reorders the columns.
Assigning with .iloc
You can assign through .iloc with the same selectors. A single call that selects and assigns writes into the original object, with no chained indexing involved.
work = df.copy()
work.iloc[0, 2] = 710 # one cell
work.iloc[-2:, 2] = [10300, 2900] # two cells, one value each
work.iloc[:, 2] = work.iloc[:, 2] * 2 # a whole column by position
print(work["population_k"].tolist())The result is [1420, 20184, 6248, 20600, 5800]. The copy() call keeps df unchanged for the other examples. The list on the right side of a multi-cell assignment must match the length of the selection.
Choosing between .iloc, .loc, and brackets
Good uses for .iloc are "the first N rows", "the last row", "every other row", and selecting columns by their order in a file whose headers are missing or unreliable. Poor uses are anything where the position stands in for a business meaning.
Common errors
- Expecting an inclusive end.
df.iloc[1:3]returns two rows, not three. Count positions from 0 and stop before the end. - Passing a label.
df.iloc["a"]raisesTypeError, because.ilocaccepts only integers, slices, lists, boolean arrays, and callables. - Passing a boolean Series. Convert with
to_numpy()or switch to.loc. - Trusting position after a reorder. Re-check positions after
sort_values,drop, or a filter. - Assuming a slice raises on overflow. It does not. Only single integers and lists do.
Practice
Exercise
Which rows and columns does df.iloc[1:4, 1:3] return from the DataFrame in this chapter, and why is row "e" not included?
Show answer
It returns rows b, c, and d (positions 1, 2, 3) and the columns country and population_k (positions 1 and 2). The slice stops before position 4 and before position 3 for the columns, so row e (position 4) and the continent column (position 3) are excluded, because .iloc slices exclude the end.
Exercise
Write one line that returns the last two rows and only the first two columns, selected by position. Then explain why df.iloc[df["population_k"] > 3000] fails and give two working alternatives.
Show answer
df.iloc[-2:, :2] returns rows d and e with the city and country columns. The second expression fails because the mask is a boolean Series, and .iloc rejects an indexed Series with a ValueError. Working alternatives are df.loc[df["populationk"] > 3000] and df.iloc[(df["populationk"] > 3000).to_numpy()].