0
0
Pandasdata~5 mins

iloc for position-based selection in Pandas

Choose your learning style9 modes available
Introduction

We use iloc to pick rows and columns from a table by their number positions, not by their names. This helps when we want to work with data based on where it is in the table.

You want to get the first 5 rows of a data table.
You want to select the 2nd and 3rd columns from a table without knowing their names.
You want to pick a single cell by its row and column number.
You want to slice a part of the table using row and column positions.
Syntax
Pandas
df.iloc[row_selection, column_selection]

row_selection and column_selection can be a single number, a list of numbers, or a slice like start:stop.

Positions start at 0, so the first row or column is at position 0.

Examples
This picks the first row of the table.
Pandas
df.iloc[0]
# Selects the first row
The colon : means all rows, and 1 means the second column.
Pandas
df.iloc[:, 1]
# Selects all rows in the second column
This picks a small block from the table using row and column positions.
Pandas
df.iloc[1:4, 0:2]
# Selects rows 2 to 4 and columns 1 to 2
This picks specific rows and columns by their positions.
Pandas
df.iloc[[0, 2], [1, 3]]
# Selects rows 1 and 3, columns 2 and 4
Sample Program

This program creates a small table with names, ages, and cities. Then it shows how to use iloc to pick the first row, the entire second column, and a small block of rows and columns.

Pandas
import pandas as pd

# Create a simple data table
data = {'Name': ['Anna', 'Bob', 'Cara', 'Dan'],
        'Age': [23, 35, 45, 28],
        'City': ['NY', 'LA', 'Chicago', 'Houston']}
df = pd.DataFrame(data)

# Select the first row
first_row = df.iloc[0]

# Select the second column for all rows
second_column = df.iloc[:, 1]

# Select rows 1 to 3 and columns 0 to 1
subset = df.iloc[1:4, 0:2]

print("First row:")
print(first_row)
print("\nSecond column:")
print(second_column)
print("\nSubset of rows and columns:")
print(subset)
OutputSuccess
Important Notes

Remember that iloc uses zero-based counting, so the first row or column is at position 0.

If you use a number outside the range of rows or columns, you will get an error.

You can mix single numbers, lists, and slices to select exactly what you want.

Summary

iloc lets you pick data by position, not by name.

Positions start at 0, like counting from the beginning.

You can select rows, columns, or both using numbers, lists, or slices.