5. Data Selection: loc vs iloc
Label-based row and column slicing with .loc
The .loc accessor is primarily label-based, which means that you specify rows and columns by their name or index label. When you use .loc, the selection includes the stop index, making it inclusive of the end point.
You can select by single labels, lists of labels, or label slices. If a label does not exist, Pandas will raise a KeyError.
The syntax for .loc is df.loc[row_label, column_label].
b will be included in the output.
import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data, index=['a', 'b']) # Select row 'a' and column 'Name' result = df.loc['a', 'Name'] print(result)
Integer-position based selection with .iloc
The .iloc accessor is strictly integer-position based. It ignores the index labels and looks only at the position of the rows and columns, starting from 0 to n-1.
Unlike .loc, .iloc uses standard Python slicing, meaning the stop index is exclusive. This makes it more intuitive for programmers familiar with standard Python list indexing.
The syntax for .iloc is df.iloc[row_position, column_position].
import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data) # Select first row and second column (Age) result = df.iloc[0, 1] print(result)
Key differences and common lookup warnings
Choosing between .loc and .iloc is fundamental to avoiding SettingWithCopyWarnings. Using chained indexing like df[A][B] is discouraged; always prefer .loc or .iloc.
Here is a comparison table to help you distinguish between the two accessors:
| Feature | Description |
|---|---|
| Selection Type | .loc (Labels), .iloc (Integers) |
| Endpoint | .loc (Inclusive), .iloc (Exclusive) |
| Missing Data | Both raise KeyError or IndexError |
# Best practice: Avoid chained indexing # Use this: df.loc[0, 'Age'] = 26
Assigning values to subsets safely
When updating values in a DataFrame, you must be careful not to create a View of the data when you meant to create a Copy. Using .loc allows you to modify the original object directly.
By targeting the exact location with .loc[row, col], you ensure that Pandas updates the original memory buffer of the DataFrame rather than creating a temporary intermediate copy.
Always define the target subset in a single instruction to guarantee stability.
import pandas as pd df = pd.DataFrame({'Score': [10, 20]}, index=['x', 'y']) # Update score for row x df.loc['x', 'Score'] = 15 print(df)
Knowledge Check
Ready to test your understanding of 5. Data Selection: loc vs iloc?