Concatenation of Data Objects
Concatenation stacks two or more DataFrames together - either on top of each other (adding more rows) or side by side (adding more columns). Unlike merging, it doesn't require a shared key column.
Stacking Rows (Vertical Concatenation)
import pandas as pd
batch1 = pd.DataFrame({"Name": ["Abhay", "Priya"], "Score": [85, 92]})
batch2 = pd.DataFrame({"Name": ["Rohit", "Simran"], "Score": [78, 88]})
combined = pd.concat([batch1, batch2], ignore_index=True)
print(combined)
# Name Score
# 0 Abhay 85
# 1 Priya 92
# 2 Rohit 78
# 3 Simran 88
Stacking Columns (Horizontal Concatenation)
contact_info = pd.DataFrame({"Phone": ["9876543210", "9876543211"]})
result = pd.concat([batch1, contact_info], axis=1)
Handling Mismatched Columns
# If column names don't match exactly, missing values become NaN
df_a = pd.DataFrame({"Name": ["Abhay"], "Score": [85]})
df_b = pd.DataFrame({"Name": ["Priya"], "Grade": ["A"]})
result = pd.concat([df_a, df_b], ignore_index=True)
print(result)
# Name Score Grade
# 0 Abhay 85.0 NaN
# 1 Priya NaN A
Use concat() when you're stacking data with the same structure from different sources (like two months of sales records) - use merge() when you're combining different information about the same entities using a shared key.
Coming Up Next
Next, you'll dig deeper into the different types of joins available while merging data objects.