0
0
Pandasdata~10 mins

loc vs iloc mental model in Pandas - Visual Side-by-Side Comparison

Choose your learning style9 modes available
Concept Flow - loc vs iloc mental model
Start with DataFrame
Use loc: label-based
Select rows/cols by labels
Use iloc: position-based
Select rows/cols by integer index
Return selected data
End
The flow shows starting with a DataFrame, then choosing loc for label-based selection or iloc for position-based selection, and finally returning the selected data.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({
  'A': [10, 20, 30],
  'B': [40, 50, 60]
}, index=['x', 'y', 'z'])

print(df.loc['y'])
print(df.iloc[1])
This code creates a DataFrame with labels x,y,z and selects the row labeled 'y' using loc and the row at position 1 using iloc.
Execution Table
StepOperationInputSelection MethodResult
1Create DataFrame{'A':[10,20,30],'B':[40,50,60]}, index=['x','y','z']N/ADataFrame with rows x,y,z and columns A,B
2Select row with loclabel='y'loc (label-based)Row with index 'y': A=20, B=50
3Select row with ilocposition=1iloc (position-based)Row at position 1: A=20, B=50
4Select row with loclabel='z'loc (label-based)Row with index 'z': A=30, B=60
5Select row with ilocposition=2iloc (position-based)Row at position 2: A=30, B=60
6Select row with loclabel='x'loc (label-based)Row with index 'x': A=10, B=40
7Select row with ilocposition=0iloc (position-based)Row at position 0: A=10, B=40
8Try loc with non-existing labellabel='a'loc (label-based)KeyError (label 'a' not found)
9Try iloc with out-of-range positionposition=5iloc (position-based)IndexError (position 5 out of range)
10EndN/AN/ASelection complete
💡 Execution stops after all selections and errors are demonstrated.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6After Step 7
dfundefinedDataFrame with index x,y,z and columns A,BSameSameSameSameSameSame
selected_rowundefinedundefined{A:20, B:50} (loc 'y'){A:20, B:50} (iloc 1){A:30, B:60} (loc 'z'){A:30, B:60} (iloc 2){A:10, B:40} (loc 'x'){A:10, B:40} (iloc 0)
Key Moments - 3 Insights
Why does df.loc['y'] and df.iloc[1] return the same row?
Because the label 'y' is at position 1 in the DataFrame index, so loc with label 'y' and iloc with position 1 select the same row (see execution_table rows 2 and 3).
What happens if you use loc with a label that does not exist?
A KeyError occurs because loc expects exact labels present in the index (see execution_table row 8).
What happens if you use iloc with a position outside the DataFrame range?
An IndexError occurs because iloc expects integer positions within the DataFrame size (see execution_table row 9).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 3. What row does df.iloc[1] select?
ARow with index 'z' (A=30, B=60)
BRow with index 'x' (A=10, B=40)
CRow with index 'y' (A=20, B=50)
DKeyError
💡 Hint
Check execution_table row 3 under Result column.
At which step does using loc cause an error due to a missing label?
AStep 8
BStep 9
CStep 7
DStep 10
💡 Hint
Look for KeyError in execution_table rows.
If you want to select the first row by position, which method and index do you use?
Aloc with label 'x'
Biloc with position 0
Cloc with label 'y'
Diloc with position 1
💡 Hint
Check variable_tracker for iloc position 0 and corresponding row.
Concept Snapshot
pandas loc vs iloc quick guide:
- loc selects by label (index names)
- iloc selects by integer position (0-based)
- loc raises KeyError if label missing
- iloc raises IndexError if position out of range
- Use loc for named indexes, iloc for position-based access
Full Transcript
This visual execution shows how pandas loc and iloc select rows from a DataFrame. We start with a DataFrame with index labels x,y,z. Using loc with label 'y' selects the row labeled 'y'. Using iloc with position 1 selects the second row by position, which is also 'y'. We see that loc uses labels and iloc uses integer positions. Errors occur if loc uses a missing label or iloc uses an invalid position. Variable tracking shows the selected rows at each step. This helps understand the difference between label-based and position-based selection in pandas.