Bird
Raised Fist0
Pandasdata~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main difference between loc and iloc in pandas?
easy
A. loc uses labels, iloc uses integer positions
B. loc uses integer positions, iloc uses labels
C. loc selects columns only, iloc selects rows only
D. loc is faster than iloc

Solution

  1. Step 1: Understand loc selection method

    loc selects data by row and column labels, meaning it uses the actual names of rows and columns.
  2. Step 2: Understand iloc selection method

    iloc selects data by integer positions, starting from 0, ignoring labels.
  3. Final Answer:

    loc uses labels, iloc uses integer positions -> Option A
  4. Quick Check:

    loc = labels, iloc = positions [OK]
Hint: Remember: loc = labels, iloc = integer positions [OK]
Common Mistakes:
  • Confusing labels with positions
  • Thinking loc uses positions
  • Assuming iloc uses labels
2. Which of the following is the correct syntax to select rows with labels 'a' to 'c' and columns 'x' to 'z' using loc?
easy
A. df.loc['a':'c', 'x':'z']
B. df.iloc['a':'c', 'x':'z']
C. df.loc[0:2, 0:2]
D. df.iloc[0:2, 'x':'z']

Solution

  1. Step 1: Identify loc syntax

    loc uses labels, so slicing with labels like 'a':'c' and 'x':'z' is valid.
  2. Step 2: Check other options

    Selections using iloc with label slices are invalid because iloc requires integer positions. Using integer slices with loc is incorrect when the labels are strings like 'a', 'c', etc.
  3. Final Answer:

    df.loc['a':'c', 'x':'z'] -> Option A
  4. Quick Check:

    loc uses labels in slices [OK]
Hint: Use labels inside loc brackets, positions inside iloc [OK]
Common Mistakes:
  • Using integer positions with loc
  • Using labels with iloc
  • Mixing loc and iloc syntax
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'A':[10,20,30], 'B':[40,50,60]}, index=['x','y','z'])

What is the output of df.iloc[1, 0]?
medium
A. 30
B. 40
C. 50
D. 20

Solution

  1. Step 1: Understand DataFrame structure

    Rows are labeled 'x','y','z' with values in column 'A' as [10,20,30]. Positions start at 0, so row 1 is 'y', column 0 is 'A'.
  2. Step 2: Apply iloc selection

    df.iloc[1, 0] selects row at position 1 ('y') and column at position 0 ('A'), value is 20.
  3. Final Answer:

    20 -> Option D
  4. Quick Check:

    iloc uses positions: row 1, col 0 = 20 [OK]
Hint: iloc uses zero-based positions, count rows and columns from 0 [OK]
Common Mistakes:
  • Using labels instead of positions
  • Confusing row and column indices
  • Selecting wrong cell by mixing loc and iloc
4. Consider this code:
import pandas as pd
df = pd.DataFrame({'A':[1,2,3]}, index=[10,20,30])
print(df.loc[1])

What error will occur and why?
medium
A. No error, prints 2
B. KeyError because label 1 does not exist in index
C. IndexError because position 1 is out of range
D. TypeError because loc expects string labels

Solution

  1. Step 1: Check DataFrame index labels

    Index labels are [10, 20, 30], so label 1 is not present.
  2. Step 2: Understand loc behavior

    loc looks for label 1, which does not exist, causing a KeyError.
  3. Final Answer:

    KeyError because label 1 does not exist in index -> Option B
  4. Quick Check:

    loc needs existing labels, else KeyError [OK]
Hint: loc needs exact labels; missing label causes KeyError [OK]
Common Mistakes:
  • Thinking loc uses positions
  • Expecting no error when label missing
  • Confusing KeyError with IndexError
5. You have a DataFrame with non-numeric row labels:
import pandas as pd
df = pd.DataFrame({'Score':[88, 92, 95]}, index=['John', 'Jane', 'Doe'])

You want to select the second row using loc and iloc. Which code will correctly select the second row and what will be the difference in output?
hard
A. df.loc['Jane'] and df.iloc['Jane'] both select by label 'Jane'; output differs
B. df.loc[1] selects by position 1; df.iloc['Jane'] selects by label 'Jane'; both return the same row
C. df.loc['Jane'] selects by label 'Jane'; df.iloc[1] selects by position 1; both return the same row
D. df.loc[1] and df.iloc[1] both select by position 1; output differs

Solution

  1. Step 1: Understand row labels and positions

    Rows are labeled 'John', 'Jane', 'Doe' at positions 0, 1, 2 respectively.
  2. Step 2: Use loc and iloc correctly

    df.loc['Jane'] selects row with label 'Jane'. df.iloc[1] selects row at position 1, which is also 'Jane'. Both return the same row.
  3. Final Answer:

    df.loc['Jane'] selects by label 'Jane'; df.iloc[1] selects by position 1; both return the same row -> Option C
  4. Quick Check:

    loc uses label, iloc uses position; same row here [OK]
Hint: loc needs label, iloc needs position; same row if label matches position [OK]
Common Mistakes:
  • Using integer with loc
  • Using label with iloc
  • Assuming loc and iloc always differ
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard