Merging DataFrames
Relational Theory Concepts
Database Terminology
- Full Outer Join (Union): Includes all individuals from both sets (students and staff).
- Inner Join (Intersection): Includes only individuals who are both students and staff.
- Left Join: Includes all records from the left set (e.g., students) and the matched records from the right set (e.g., staff). If there is no match, the result will have
NULLon the side of the right set. - Right Join: Includes all records from the right set (e.g., staff) and the matched records from the left set (e.g., students). If there is no match, the result will have
NULLon the side of the left set.
Merging DataFrames in Pandas
Creating Sample DataFrames
import pandas as pd
# Staff DataFrame
staff_df = pd.DataFrame([
{'Name': 'Kelly', 'Role': 'Director of HR'},
{'Name': 'Sally', 'Role': 'Course liaison'},
{'Name': 'James', 'Role': 'Grader'}
]).set_index('Name')
# Student DataFrame
student_df = pd.DataFrame([
{'Name': 'James', 'School': 'Business'},
{'Name': 'Mike', 'School': 'Law'},
{'Name': 'Sally', 'School': 'Engineering'}
]).set_index('Name')
print(staff_df.head())
print(student_df.head())
Full Outer Join (Union)
# Union of the DataFrames
pd.merge(staff_df, student_df, how='outer', left_index=True, right_index=True)
Inner Join (Intersection)
# Intersection of the DataFrames
pd.merge(staff_df, student_df, how='inner', left_index=True, right_index=True)
Left Join
# Left Join (all staff and their student details if applicable)
pd.merge(staff_df, student_df, how='left', left_index=True, right_index=True)
Right Join
# Right Join (all students and their staff details if applicable)
pd.merge(staff_df, student_df, how='right', left_index=True, right_index=True)
Merging on Columns
# Reset index for merging on columns
staff_df = staff_df.reset_index()
student_df = student_df.reset_index()
# Merge using the 'Name' column
pd.merge(staff_df, student_df, how='right', on='Name')
Handling Conflicts with Suffixes
# New DataFrames with Location information
staff_df = pd.DataFrame([
{'Name': 'Kelly', 'Role': 'Director of HR', 'Location': 'State Street'},
{'Name': 'Sally', 'Role': 'Course liaison', 'Location': 'Washington Avenue'},
{'Name': 'James', 'Role': 'Grader', 'Location': 'Washington Avenue'}
])
student_df = pd.DataFrame([
{'Name': 'James', 'School': 'Business', 'Location': '1024 Billiard Avenue'},
{'Name': 'Mike', 'School': 'Law', 'Location': 'Fraternity House #22'},
{'Name': 'Sally', 'School': 'Engineering', 'Location': '512 Wilson Crescent'}
])
# Merge with conflicts resolved by suffixes
pd.merge(staff_df, student_df, how='left', on='Name')