loc vs iloc mental model in Pandas - Performance Comparison
We want to understand how the time it takes to select data with loc and iloc changes as the data grows.
How does the size of the data affect the speed of these selection methods?
Analyze the time complexity of selecting rows and columns using loc and iloc.
import pandas as pd
df = pd.DataFrame({
'A': range(1000),
'B': range(1000, 2000),
'C': range(2000, 3000)
})
# Using loc to select rows by label
subset_loc = df.loc[100:199, ['A', 'B']]
# Using iloc to select rows by position
subset_iloc = df.iloc[100:200, 0:2]
This code selects 100 rows and 2 columns from a DataFrame of 1000 rows and 3 columns using both label-based and position-based indexing.
Look at what repeats when selecting data.
- Primary operation: Accessing each requested row and column in the DataFrame.
- How many times: For 100 rows and 2 columns, 200 data points are accessed.
As the number of rows or columns you select grows, the work grows roughly in the same way.
| Input Size (rows x columns) | Approx. Operations |
|---|---|
| 10 x 2 | 20 |
| 100 x 2 | 200 |
| 1000 x 2 | 2000 |
Pattern observation: The number of operations grows proportionally with the number of selected rows and columns.
Time Complexity: O(k)
This means the time to select data grows linearly with the size of the selection, not the whole DataFrame.
[X] Wrong: "Selecting data with loc or iloc always scans the entire DataFrame, so it takes the same time no matter what."
[OK] Correct: Both methods access only the requested rows and columns, so the time depends on the size of the selection, not the full data.
Understanding how data selection scales helps you write efficient code and explain your choices clearly in real projects and interviews.
What if we changed the selection to include all rows but only one column? How would the time complexity change?
Practice
loc and iloc in pandas?Solution
Step 1: Understand
locselection methodlocselects data by row and column labels, meaning it uses the actual names of rows and columns.Step 2: Understand
ilocselection methodilocselects data by integer positions, starting from 0, ignoring labels.Final Answer:
locuses labels,ilocuses integer positions -> Option AQuick Check:
loc = labels, iloc = positions [OK]
- Confusing labels with positions
- Thinking loc uses positions
- Assuming iloc uses labels
loc?Solution
Step 1: Identify
locsyntaxlocuses labels, so slicing with labels like 'a':'c' and 'x':'z' is valid.Step 2: Check other options
Selections usingilocwith label slices are invalid becauseilocrequires integer positions. Using integer slices withlocis incorrect when the labels are strings like 'a', 'c', etc.Final Answer:
df.loc['a':'c', 'x':'z'] -> Option AQuick Check:
loc uses labels in slices [OK]
- Using integer positions with loc
- Using labels with iloc
- Mixing loc and iloc syntax
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]?Solution
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'.Step 2: Apply
ilocselectiondf.iloc[1, 0]selects row at position 1 ('y') and column at position 0 ('A'), value is 20.Final Answer:
20 -> Option DQuick Check:
iloc uses positions: row 1, col 0 = 20 [OK]
- Using labels instead of positions
- Confusing row and column indices
- Selecting wrong cell by mixing loc and iloc
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?
Solution
Step 1: Check DataFrame index labels
Index labels are [10, 20, 30], so label 1 is not present.Step 2: Understand
locbehaviorloclooks for label 1, which does not exist, causing a KeyError.Final Answer:
KeyError because label 1 does not exist in index -> Option BQuick Check:
loc needs existing labels, else KeyError [OK]
- Thinking loc uses positions
- Expecting no error when label missing
- Confusing KeyError with IndexError
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?Solution
Step 1: Understand row labels and positions
Rows are labeled 'John', 'Jane', 'Doe' at positions 0, 1, 2 respectively.Step 2: Use
locandiloccorrectlydf.loc['Jane']selects row with label 'Jane'.df.iloc[1]selects row at position 1, which is also 'Jane'. Both return the same row.Final Answer:
df.loc['Jane']selects by label 'Jane';df.iloc[1]selects by position 1; both return the same row -> Option CQuick Check:
loc uses label, iloc uses position; same row here [OK]
- Using integer with loc
- Using label with iloc
- Assuming loc and iloc always differ
Ready to prove it?
Pass the test and this pattern moves unknown
