Explain how inner and left joins work in Python and provide examples.
π‘ Model Answer
In pandas, joins are performed using the merge function, which aligns rows from two DataFrames based on key columns. An inner join returns only rows with matching keys in both DataFrames, analogous to SQL's INNER JOIN. A left join (or left outer join) returns all rows from the left DataFrame and matches from the right; unmatched rows get NaN.
Example:
import pandas as pd
# Left DataFrame
left = pd.DataFrame({
'id': [1, 2, 3],
'name': ['Alice', 'Bob', 'Charlie']
})
# Right DataFrame
right = pd.DataFrame({
'id': [2, 3, 4],
'score': [88, 92, 75]
})
# Inner join on 'id'
inner = pd.merge(left, right, on='id', how='inner')
print('Inner join:\n', inner)
# Left join on 'id'
left_join = pd.merge(left, right, on='id', how='left')
print('\nLeft join:\n', left_join)Output:
Inner join:
id name score
0 2 Bob 88
1 3 Charlie 92
Left join:
id name score
0 1 Alice NaN
1 2 Bob 88.0
2 3 Charlie 92.0Key points: how='inner' keeps only matching keys; how='left' keeps all left keys. You can also specify right, outer, or cross for other join types. Understanding these options lets you manipulate relational data efficiently in pandas.
This answer was generated by AI for study purposes. Use it as a starting point β personalize it with your own experience.
π€ Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers β invisible to screen sharing.
Get Assisting AI β Starts at βΉ500