0
0
Pandasdata~5 mins

loc vs iloc mental model in Pandas

Choose your learning style9 modes available
Introduction

We use loc and iloc to pick rows and columns from tables in pandas. They help us get exactly the data we want.

When you want to select data by row and column labels (names).
When you want to select data by row and column positions (numbers).
When you want to slice parts of a table using labels or positions.
When you want to filter data based on index or column names.
When you want to avoid mistakes by clearly choosing label-based or position-based selection.
Syntax
Pandas
df.loc[row_label, column_label]
df.iloc[row_position, column_position]

loc uses the actual names of rows and columns.

iloc uses the number positions starting from 0.

Examples
Selects the value where row label is 'row1' and column label is 'colA'.
Pandas
df.loc['row1', 'colA']
Selects the value at first row (position 0) and second column (position 1).
Pandas
df.iloc[0, 1]
Selects rows from 'row1' to 'row3' and columns from 'colA' to 'colC' inclusive.
Pandas
df.loc['row1':'row3', 'colA':'colC']
Selects first 3 rows and first 2 columns by position (end exclusive).
Pandas
df.iloc[0:3, 0:2]
Sample Program

This code shows how to pick single values and slices from a table using loc and iloc. It uses labels for loc and positions for iloc.

Pandas
import pandas as pd

# Create a simple DataFrame with labels
data = {'colA': [10, 20, 30], 'colB': [40, 50, 60], 'colC': [70, 80, 90]}
index_labels = ['row1', 'row2', 'row3']
df = pd.DataFrame(data, index=index_labels)

# Using loc to select by labels
val_loc = df.loc['row2', 'colB']

# Using iloc to select by positions
val_iloc = df.iloc[1, 1]

# Using loc to slice rows and columns by labels
slice_loc = df.loc['row1':'row2', 'colA':'colB']

# Using iloc to slice rows and columns by positions
slice_iloc = df.iloc[0:2, 0:2]

print('Value with loc:', val_loc)
print('Value with iloc:', val_iloc)
print('\nSlice with loc:')
print(slice_loc)
print('\nSlice with iloc:')
print(slice_iloc)
OutputSuccess
Important Notes

loc includes the last label in slices (end is inclusive).

iloc excludes the last position in slices (end is exclusive).

If your DataFrame index is numbers starting from 0, loc and iloc can give different results.

Summary

loc selects data by row and column labels.

iloc selects data by row and column positions (numbers starting at 0).

Use loc when you know the names, and iloc when you want to use positions.