ZetCode

Pandas iloc Function

last modified November 17, 2026 Python 3.15

Pandas is a Python library for working with tabular data. The iloc indexer selects rows and columns by their integer positions, counting from zero. It is one of the basic tools for picking a subset out of a DataFrame.

A position is a row or column's place in the table, while a label is the name stored in the index or in the columns. The examples below use a DataFrame with string index labels on purpose, so that position-based selection is clearly different from label-based selection.

Selecting rows by position

Passing a single integer to iloc selects one row by position. The result is a Series: a one-dimensional object whose index holds the column names and whose values are the cells of that row.

iloc_rows.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
    'age': [25, 30, 35, 28, 33],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin']
}
df = pd.DataFrame(data, index=['r1', 'r2', 'r3', 'r4', 'r5'])

print(df.iloc[0])
print()
print(df.iloc[2])

The expression df.iloc[0] returns the first row, and df.iloc[2] returns the third row. Notice that the printed Name is the label r1 or r3 even though we asked for position 0 or 2; the label is preserved in the result.

$ python iloc_rows.py
name     Alice
age         25
city    Prague
Name: r1, dtype: object

name    Charlie
age          35
city     London
Name: r3, dtype: object

Integer slicing is end-exclusive

A slice is a range written as start:stop. With iloc the range is end-exclusive: the row at position stop is not included. This is the same rule Python uses for slicing a list.

iloc_slice.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
    'age': [25, 30, 35, 28, 33],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin']
}
df = pd.DataFrame(data, index=['r1', 'r2', 'r3', 'r4', 'r5'])

print(df.iloc[1:4])

The slice 1:4 selects positions 1, 2 and 3, which are the rows labelled r2, r3 and r4. The row at position 4 (r5) is left out. Leaving out one end of the slice means "from the start" or "up to the end".

$ python iloc_slice.py
       name  age        city
r2      Bob   30  Bratislava
r3  Charlie   35      London
r4    Diana   28       Paris

Negative indexes

Negative positions count backwards from the end of the table: -1 is the last row, -2 the second-to-last, and so on. This makes it easy to select the newest or final records without knowing how many rows there are.

iloc_negative.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
    'age': [25, 30, 35, 28, 33],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin']
}
df = pd.DataFrame(data, index=['r1', 'r2', 'r3', 'r4', 'r5'])

print(df.iloc[-1])
print()
print(df.iloc[-2:])

Here df.iloc[-1] gives the single last row. The slice -2: means "from the second-to-last row through to the end", so it returns the final two rows. Negative slices still follow the end-exclusive rule when a stop value is given.

$ python iloc_negative.py
name       Eve
age         33
city    Berlin
Name: r5, dtype: object

     name  age    city
r4  Diana   28   Paris
r5    Eve   33  Berlin

Selecting rows and columns together

Inside the square brackets, iloc accepts two arguments separated by a comma: .iloc[rows, columns]. Each argument can be an integer, a list of integers, or a slice. This lets us narrow down both directions of the table in a single step.

iloc_rows_cols.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
    'age': [25, 30, 35, 28, 33],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin']
}
df = pd.DataFrame(data, index=['r1', 'r2', 'r3', 'r4', 'r5'])

print(df.iloc[0:3, 0:2])
print()
print(df.iloc[1, 2])

The first expression takes rows at positions 0 to 2 and columns at positions 0 and 1, so it returns a smaller DataFrame. The second expression uses two integers, which selects one cell and returns a single scalar value, Bratislava, rather than a DataFrame or a Series. A colon on its own, as in df.iloc[:, 0], means "all rows".

$ python iloc_rows_cols.py
       name  age
r1    Alice   25
r2      Bob   30
r3  Charlie   35

Bratislava

Difference from label-based loc

Pandas also provides the loc indexer, which selects by label instead of by position. With a string index, loc needs the label r2 where iloc needs the integer 1. With an integer index the two can look identical but still slice differently: loc includes the stop label, while iloc does not.

iloc_vs_loc.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
    'age': [25, 30, 35, 28, 33],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin']
}
df = pd.DataFrame(data, index=['r1', 'r2', 'r3', 'r4', 'r5'])

print(df.loc['r2'])
print()
print(df.iloc[1])
print()

df2 = pd.DataFrame({'value': [10, 20, 30, 40]}, index=[0, 1, 2, 3])
print(df2.loc[1:2])
print()
print(df2.iloc[1:2])

The first two results are the same row reached two different ways: by the label r2 and by position 1. In the second part, df2.loc[1:2] returns the rows labelled 1 and 2, whereas df2.iloc[1:2] returns only position 1. The rule to remember is: use iloc when you think in positions, and loc when you think in labels.

$ python iloc_vs_loc.py
name           Bob
age             30
city    Bratislava
Name: r2, dtype: object

name           Bob
age             30
city    Bratislava
Name: r2, dtype: object

   value
1     20
2     30

   value
1     20

The IndexError trap

A position that does not exist raises an IndexError when you use a single integer. This is a common trap because a slice that goes past the end does not raise an error; it simply returns an empty result. The example catches the exception so that the script can keep running and show both behaviours.

iloc_error.py
import pandas as pd

data = {
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
    'age': [25, 30, 35, 28, 33],
    'city': ['Prague', 'Bratislava', 'London', 'Paris', 'Berlin']
}
df = pd.DataFrame(data, index=['r1', 'r2', 'r3', 'r4', 'r5'])

try:
    df.iloc[10]
except IndexError as e:
    print(type(e).__name__ + ':', e)

print()
print('slice past end:', df.iloc[10:].shape)

The DataFrame has only five rows, so position 10 is out of bounds and IndexError is raised. In contrast, df.iloc[10:] produces a valid empty DataFrame; its shape attribute reports zero rows and three columns. If a selection must succeed, check the length of the DataFrame or guard the access with try/except.

$ python iloc_error.py
IndexError: single positional indexer is out-of-bounds

slice past end: (0, 3)

Source

Pandas iloc Documentation

In this article we have shown how to select data by integer position with iloc, including slices, negative indexes, two-dimensional selection, and the difference from label-based indexing. For label-based selection see the Pandas loc tutorial, and for filtering rows by conditions see Pandas boolean indexing.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pandas tutorials.