loc and iloc
Access specific rows and columns using label-based loc and position-based iloc for precise data selection.
- Use loc to select rows and columns by label
- Use iloc to select rows and columns by integer position
- Combine row and column selection in a single operation
- Use loc for targeted assignment and editing
The problem with bracket indexing
Basic bracket indexing df[mask] works for row filtering and df["col"] for column selection. But when you need to select specific rows and specific columns in one step, or edit individual cells, you need loc and iloc.
import pandas as pd
# titanic.csv ships with the course — load it from the browser file system.
df = pd.read_csv("titanic.csv")loc: label-based selection
loc selects by label, the row index labels and column names:
# Select row at index label 0, columns "Name" and "Age"
print(df.loc[0, ["Name", "Age"]])Output:
Name Braund, Mr. Owen Harris
Age 22.0
Name: 0, dtype: object
Slice by label, the endpoint is inclusive (unlike Python slicing):
# Rows 0 through 4, columns Name through Age
print(df.loc[0:4, "Name":"Age"])Select all rows for specific columns:
print(df.loc[:, ["Name", "Survived"]].head())Select all columns for specific rows:
print(df.loc[[0, 5, 10]])iloc: position-based selection
iloc selects by integer position, the row/column number starting from 0:
# First row, first three columns
print(df.iloc[0, :3])Output:
PassengerId 1
Survived 0
Pclass 3
Name: 0, dtype: object
Slice by position, the endpoint is exclusive (standard Python behavior):
# Rows 0-4 (5 rows), columns 0-2 (3 columns)
print(df.iloc[0:5, 0:3])Select specific rows and columns:
# Rows 0, 1, 5; columns 3 (Name) and 4 (Age)
print(df.iloc[[0, 1, 5], [3, 4]])loc vs iloc: key differences
| Feature | loc | iloc |
|---|---|---|
| Selection by | Labels (names) | Integer positions |
| Slice endpoint | Inclusive | Exclusive |
| Column selection | By name | By position |
| Best for | Named indices | Default integer index |
# These are different:
df.loc[0:5] # rows with labels 0 through 5 (inclusive) — 6 rows
df.iloc[0:5] # rows at positions 0 through 4 (exclusive) — 5 rowsUsing loc for assignment
loc is not just for reading, you can use it to edit specific cells:
# Set Age to 0 for the first passenger
df.loc[0, "Age"] = 0
# Set Fare to -1 for rows where Fare is negative
df.loc[df["Fare"] < 0, "Fare"] = 0
# Create a new column based on conditions
df.loc[df["Age"] < 18, "Category"] = "Minor"
df.loc[df["Age"] >= 18, "Category"] = "Adult"This targeted editing is essential for data cleaning.
Practical patterns
Get a specific cell value:
# The name of the passenger at position 100
name = df.loc[100, "Name"]
print(name)Select a range of columns:
# All rows, columns from "Name" to "Fare"
print(df.loc[:, "Name":"Fare"].head())Conditional selection with both axes:
# Female passengers, only Name and Age columns
women = df.loc[df["Sex"] == "female", ["Name", "Age"]]
print(women.head())Try It
From the Titanic dataset:
- Use
ilocto print the first 3 rows and first 4 columns - Use
locto print the Name and Fare of the passenger at index 50 - Use
locto set the Age of the passenger at index 0 to 25
import pandas as pd
# titanic.csv ships with the course — load it from the browser file system.
df = pd.read_csv("titanic.csv")
# First 3 rows, first 4 columns
print(df.iloc[0:3, 0:4])
# Name and Fare at index 50
print(df.loc[50, ["Name", "Fare"]])
# Set Age to 25
df.loc[0, "Age"] = 25
print(df.loc[0, "Age"])Key Takeaways
locselects by label (names);ilocselects by integer positionlocslices are inclusive on both ends;ilocslices follow Python convention (exclusive end)locsupports assignment for targeted cell editing- Combining row and column selection in one
loccall is cleaner than chained indexing
Practice Challenge
From the Titanic dataset, use iloc to extract rows 100-109 and columns 2-5 (Pclass through Age). Then use loc to find the names of all passengers with index labels 0, 50, 100, and 500. Finally, use loc to change the Fare of passenger at index 7 to 999 and verify the change.
1. What is the difference between loc and iloc?
2. How do you select the first 3 rows with iloc?
3. How do you select a specific cell with loc?