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.
iloc for position-based selection in 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.
df.iloc[0] # Selects the first row
: means all rows, and 1 means the second column.df.iloc[:, 1] # Selects all rows in the second column
df.iloc[1:4, 0:2] # Selects rows 2 to 4 and columns 1 to 2
df.iloc[[0, 2], [1, 3]] # Selects rows 1 and 3, columns 2 and 4
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.
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)
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.
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.