In this lesson, you will learn how to transition from basic column selection to precise, granular control over individual DataFrame cells using loc and iloc.
When you need to extract or modify a specific value in a DataFrame, you must distinguish between the name of the data and its physical position. In pandas, loc and iloc serve as your primary tools for this surgery.
Label-Based Indexing with loc
loc is purely label-based. When you use df.loc[row_label, column_label], you are telling pandas to find the exact index and column names you provided. This is robust because it doesn't matter where those items are located in the DataFrame; as long as the labels exist, loc will retrieve them.
import pandas as pd
df = pd.DataFrame({'Score': [85, 90]}, index=['Alice', 'Bob'])
# Retrieve Alice's Score using her label
score = df.loc['Alice', 'Score']
Position-Based Indexing with iloc
iloc is strictly position-based (integer-based), similar to standard NumPy array indexing. df.iloc[row_index, column_index] focuses on the numerical coordinates. This is essential when you don't care about the labels and simply need the value located, for example, in the first row and the first column (index 0, 0).
# Retrieve the value in the first row, first column
value = df.iloc[0, 0]
Why the Distinction Matters
The critical difference arises during updates. If you re-sort your DataFrame or add new rows, the position of a value changes, but its label remains constant. If you rely on iloc, your code might suddenly point to the wrong data after a sort operation. Conversely, if your labels are non-unique or confusing, iloc provides a stable, deterministic way to interact with the underlying memory structure.
For advanced workflows, using these accessors is significantly more efficient and safer than chained indexing (like df['col'][row]), which can trigger a SettingWithCopyWarning and lead to unpredictable performance issues when you attempt to modify the underlying data.
Key Takeaway: Use loc when targeting specific indices or column names for clarity, and use iloc when performing position-based operations that must remain independent of label naming conventions.