Merging of Data Objects
In real projects, related data is often split across multiple files or tables - student details in one file, their marks in another. Merging lets you combine such DataFrames based on a common column, just like a join in SQL.
A Basic Merge
import pandas as pd
students = pd.DataFrame({
"StudentID": [1, 2, 3],
"Name": ["Abhay", "Priya", "Rohit"]
})
marks = pd.DataFrame({
"StudentID": [1, 2, 3],
"Score": [85, 92, 78]
})
merged = pd.merge(students, marks, on="StudentID")
print(merged)
# StudentID Name Score
# 0 1 Abhay 85
# 1 2 Priya 92
# 2 3 Rohit 78
Merging on Differently Named Columns
merged2 = pd.merge(students, marks, left_on="StudentID", right_on="StudentID")
# If the key columns have different names:
merged3 = pd.merge(df_a, df_b, left_on="ID", right_on="StudentID")
Merging on Multiple Columns
result = pd.merge(df_a, df_b, on=["StudentID", "Year"])
Coming Up Next
Next, you'll learn about concatenation - stacking DataFrames together instead of joining them on a key.