Merging on index in Pandas - Time & Space Complexity
When we combine two tables by matching their row labels, it takes some time depending on how big the tables are.
We want to understand how the time needed grows as the tables get bigger.
Analyze the time complexity of the following code snippet.
import pandas as pd
n = 10 # Example size
# Create two dataframes with indexes
left = pd.DataFrame({'A': range(n)}, index=range(n))
right = pd.DataFrame({'B': range(n)}, index=range(n))
# Merge on index
result = pd.merge(left, right, left_index=True, right_index=True)
This code merges two dataframes by matching their indexes, combining rows with the same index label.
- Primary operation: Checking each index in one dataframe and finding the matching index in the other.
- How many times: Once for each row in the first dataframe, so n times.
As the number of rows grows, the work to match indexes grows roughly in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 index matches |
| 100 | About 100 index matches |
| 1000 | About 1000 index matches |
Pattern observation: The number of operations grows directly with the number of rows.
Time Complexity: O(n)
This means the time to merge grows in a straight line as the number of rows increases.
[X] Wrong: "Merging on index is instant no matter how big the dataframes are."
[OK] Correct: Even though indexes help find matches quickly, the operation still needs to check each row, so it takes longer as the data grows.
Understanding how merging on index scales helps you explain data combining tasks clearly and shows you know how data size affects performance.
"What if the indexes were not sorted or unique? How would the time complexity change?"
Practice
left_index=True and right_index=True do when merging two pandas DataFrames?Solution
Step 1: Understand the role of indexes in merge
Indexes are row labels in pandas DataFrames. Usingleft_index=Trueandright_index=Truetells pandas to join on these row labels instead of columns.Step 2: Effect of these parameters in merge
When both are True, pandas matches rows based on their index values, combining rows with the same index from both DataFrames.Final Answer:
It merges the DataFrames using their row indexes as the key. -> Option DQuick Check:
Merging on indexes = left_index=True and right_index=True [OK]
- Thinking merge always uses columns as keys
- Confusing index merge with concatenation
- Ignoring the need to set both left_index and right_index
df1 and df2 on their indexes with an inner join?Solution
Step 1: Identify correct parameters for index merge
To merge on indexes, pandas requiresleft_index=Trueandright_index=True. Usingon='index'orleft_on='index'is incorrect because 'index' is not a column name.Step 2: Confirm the join type
Thehow='inner'parameter specifies an inner join, which keeps only matching index rows.Final Answer:
pd.merge(df1, df2, left_index=True, right_index=True, how='inner') -> Option BQuick Check:
Use left_index and right_index for index merge [OK]
- Using on='index' instead of left_index=True
- Confusing index merge with column merge
- Forgetting to set both left_index and right_index
df1:
A
idx
1 10
2 20
3 30
df2:
B
idx
2 200
3 300
4 400
What is the result of
pd.merge(df1, df2, left_index=True, right_index=True, how='inner')?Solution
Step 1: Understand inner join on indexes
An inner join keeps only rows where the index exists in both DataFrames. Here, indexes 2 and 3 are common.Step 2: Combine matching rows
Rows with index 2 have A=20 and B=200, index 3 have A=30 and B=300. Rows with index 1 and 4 are excluded.Final Answer:
{'idx': [2, 3], 'A': [20, 30], 'B': [200, 300]} -> Option AQuick Check:
Inner join keeps only common indexes [OK]
- Including rows with indexes not in both DataFrames
- Confusing inner join with outer join
- Expecting nulls in inner join result
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2]}, index=[0, 1])
df2 = pd.DataFrame({'B': [3, 4]}, index=[1, 2])
result = pd.merge(df1, df2, left_index=True, right_index=True, how='outer')
print(result)What is the error in this code?
Solution
Step 1: Check parameters used in merge
The code usesleft_index=Trueandright_index=Truecorrectly to merge on indexes withhow='outer'.Step 2: Understand outer join behavior
Outer join includes all indexes from both DataFrames, filling missing values with NaN. This is valid and runs without error.Final Answer:
No error; the code runs and merges correctly. -> Option AQuick Check:
left_index and right_index merge works fine [OK]
- Assuming missing 'on' causes error when using index merge
- Thinking left_index and right_index cannot be combined
- Believing indexes must match exactly for merge
df1:
Score
Student
Alice 85
Bob 90
Charlie 78
df2:
Grade
Student
Bob B
Charlie C
David A
You want to merge them so that all students from
df1 appear, and matching grades from df2 are added. Missing grades should show as NaN. Which code achieves this?Solution
Step 1: Identify merge type for all df1 rows
To keep all rows fromdf1and add matching data fromdf2, use a left join.Step 2: Merge on indexes
Both DataFrames use 'Student' as index, so setleft_index=Trueandright_index=Trueto merge on indexes.Final Answer:
pd.merge(df1, df2, left_index=True, right_index=True, how='left') -> Option CQuick Check:
Left join on indexes keeps all df1 rows [OK]
- Using inner join which drops unmatched df1 rows
- Using right join which keeps df2 rows instead
- Merging on columns instead of indexes
Ready to prove it?
Pass the test and this pattern moves unknown
