30 Mins

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].

Operator Note: Always remember that .loc is inclusive of the end range. If you slice [a:b], the row b will be included in the output.
Python 3
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].

Operator Note: Use .iloc when you need to access specific data points regardless of how your index is named or formatted.
Python 3
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:

FeatureDescription
Selection Type.loc (Labels), .iloc (Integers)
Endpoint.loc (Inclusive), .iloc (Exclusive)
Missing DataBoth raise KeyError or IndexError
Operator Note: Avoid 'chained indexing' like df[row][col] as it can lead to unpredictable behavior when modifying dataframes.
Text
# 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.

Operator Note: Direct modification via .loc is the safest way to ensure data integrity during your cleaning pipelines.
Python 3
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?

Back