Combining Data: Merging, Joining, and Concatenating
6 min read
Combining Data: Merging, Joining, and Concatenating 🐼
Welcome, data wranglers! So you've got your data in pristine DataFrames, but they're in separate files. It's like having the ingredients for a magnificent cake, but in different bowls. To bake that delicious data-cake, you need to combine them! This guide will walk you through the essential Pandas techniques for combining data: concat(), merge(), and join().
Don't worry, we'll keep it practical and focus on what you'll actually use. Let's get our hands dirty with some data alchemy!
1. Stacking DataFrames: concat() Vertically and Horizontally 🥞
The Problem: You have datasets that are structurally similar. Imagine you have sales data for January in one file and for February in another. You want to stack them on top of each other to get a combined dataset for both months. Or, you might have two datasets with the same rows but different columns of information that you want to place side-by-side.
The Solution: pd.concat() is your go-to function for this. Think of it as gluing DataFrames together. You can glue them vertically (stacking rows) or horizontally (placing columns side-by-side).
Vertical Concatenation (Stacking Rows)
This is the most common use of concat(). You're essentially adding more rows to your dataset.
Example: Let's say we have two DataFrames of sales data.
import pandas as pd
# Sales data for January
sales_jan = pd.DataFrame({
'Product': ['A', 'B', 'C'],
'Sales': [100, 150, 200]
})
# Sales data for February
sales_feb = pd.DataFrame({
'Product': ['A', 'B', 'D'],
'Sales': [120, 180, 50]
})
# Let's stack them!
all_sales = pd.concat([sales_jan, sales_feb])
print(all_sales)What's happening under the hood?
Pandas takes the DataFrames you provide in a list and stacks them along axis=0 (the rows) by default. Notice the index? It's repeated. This might not be what you want.
🔥 Pro-Tip: ignore_index=True
To create a fresh, continuous index for your new combined DataFrame, use ignore_index=True.
all_sales_new_index = pd.concat([sales_jan, sales_feb], ignore_index=True)
print(all_sales_new_index)This is a small trick that will save you a lot of headaches later on!
Horizontal Concatenation (Adding Columns)
Less common, but still useful. This is for when you want to add new columns to a DataFrame from another DataFrame. The rows should ideally represent the same entities.
Example:
# Product prices
product_prices = pd.DataFrame({
'Price': [10, 20, 15]
}, index=[0, 1, 2]) # Assuming this corresponds to the first 3 products
# Let's add prices next to our January sales
jan_sales_with_prices = pd.concat([sales_jan, product_prices], axis=1)
print(jan_sales_with_prices)Here, axis=1 tells Pandas to concatenate along the columns.
2. Database-Style Joins: Using merge() 🤝
The Problem: You have two (or more) datasets that share a common piece of information, a "key," and you want to combine them based on that key. This is the bread and butter of data combination and is very similar to JOIN in SQL. For instance, you might have a DataFrame with customer information and another with their orders. You'd want to link them using a customer_id.
The Solution: pd.merge() is the powerhouse for this. It's incredibly flexible and allows for sophisticated combining logic.
Example:
import pandas as pd
# Customer information
customers = pd.DataFrame({
'customer_id': [1, 2, 3, 4],
'name': ['Alice', 'Bob', 'Charlie', 'David']
})
# Order information
orders = pd.DataFrame({
'order_id': [101, 102, 103],
'customer_id': [1, 3, 1],
'product': ['Laptop', 'Mouse', 'Keyboard']
})
# Let's merge them to see who ordered what
customer_orders = pd.merge(customers, orders, on='customer_id')
print(customer_orders)Key Parameters in merge():
leftandright: The two DataFrames you want to merge.on: The name of the column that is the common key between the two DataFrames. This is the most straightforward way to merge.left_onandright_on: Use these if the key column has different names in the two DataFrames. For example, if one iscustomer_idand the other iscust_id.how: This is where the magic happens! It specifies the type of join to perform. Let's dive into that next.
3. Understanding Join Types: Inner, Outer, Left, and Right 🧠
The Problem: When you merge two datasets, what happens to the rows that don't have a match in the other dataset? For example, in our previous merge, what about the customers who haven't placed an order (Bob and David)? The how parameter in merge() gives you control over this.
The Solutions:
Imagine you're at a party. The "left" DataFrame is the group of people you came with, and the "right" DataFrame is another group.
Inner Join (The Default)
how='inner'- Analogy: Only the people who know someone in the other group get to be on the dance floor.
- Result: You get a DataFrame containing only the rows where the key exists in both DataFrames. In our example,
BobandDavidfrom thecustomersDataFrame are excluded because they don't have a matchingcustomer_idin theordersDataFrame.
pd.merge(customers, orders, on='customer_id', how='inner')Outer Join
how='outer'- Analogy: Everyone from both groups gets to be on the dance floor. If someone doesn't have a partner from the other group, they'll be dancing on their own (represented as
NaNvalues). - Result: You get all rows from both DataFrames. Where there's no match, the missing values are filled with
NaN(Not a Number).
pd.merge(customers, orders, on='customer_id', how='outer')Left Join
how='left'- Analogy: Everyone from your group (the "left" DataFrame) gets on the dance floor. If they have a partner from the other group, great! If not, they still get to be there.
- Result: You get all rows from the left DataFrame, and only the matching rows from the right DataFrame. Unmatched rows in the left DataFrame will have
NaNfor the columns from the right DataFrame. This is one of the most commonly used joins in practice.
pd.merge(customers, orders, on='customer_id', how='left')Right Join
how='right'- Analogy: The opposite of a left join. Everyone from the other group (the "right" DataFrame) gets on the dance floor.
- Result: You get all rows from the right DataFrame, and only the matching rows from the left DataFrame.
pd.merge(customers, orders, on='customer_id', how='right')4. Index-Based Joining: The join() Method 🔗
The Problem: Sometimes, the information you want to join on isn't in a column, but in the DataFrame's index.
The Solution: The .join() method is a convenient way to perform merges based on the index. By default, it performs a left join on the indices.
Example:
import pandas as pd
# Employee data with employee ID as the index
employees = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'department': ['HR', 'Engineering', 'Marketing']
}, index=[101, 102, 103])
# Salary data with employee ID as the index
salaries = pd.DataFrame({
'salary': [70000, 80000, 75000]
}, index=[101, 102, 104]) # Note that employee 103 is missing and 104 is extra
# Let's join them!
employee_salaries = employees.join(salaries)
print(employee_salaries)Notice how Charlie (index 103) has a NaN for salary because that index wasn't in the salaries DataFrame. The .join() method defaults to a left join.
References for Further Exploration: 📚
- Official Pandas Documentation on Merging: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html
pandas.concat()documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.htmlpandas.DataFrame.merge()documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.htmlpandas.DataFrame.join()documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html
Challenge
Challenge: Consolidate Sales and Customer Data
You are a data analyst at a retail company and have been given three pandas DataFrames:
sales_h1: Contains sales transactions from the first half of the year.sales_h2: Contains sales transactions from the second half of the year.customer_demographics: Contains demographic information for a list of customers.
Your task is to create a single, comprehensive report named full_report by performing the following two steps:
First, combine
sales_h1andsales_h2vertically into a single DataFrame calledyearly_sales. The resulting DataFrame must have a new, continuous index starting from 0.Next, combine the
yearly_salesDataFrame with thecustomer_demographicsDataFrame.- The link between the two datasets is the customer identifier. Note that the column is named
CustomerIDinyearly_salesandcustomer_idincustomer_demographics. - Your final report must retain all records from the
yearly_salesdata, filling in demographic information where available. If a customer who made a purchase is not in the demographics table, their demographic fields should be empty.
- The link between the two datasets is the customer identifier. Note that the column is named
The final, combined DataFrame should be assigned to the variable full_report.
Expected result
The final full_report DataFrame should contain 7 rows, representing all sales from the combined sales_h1 and sales_h2 DataFrames.
It should have the following columns: OrderID, CustomerID, Amount, customer_id, Age, and City.
- The row for the sale made by
CustomerID'C4' should exist, but itscustomer_id,Age, andCitycolumns should containNaNorNonevalues, as this customer is not present in thecustomer_demographicstable. - Customer 'C5' from the
customer_demographicstable should not appear in the final report because they have no corresponding sales records inyearly_sales.
The final output should look like this:
| OrderID | CustomerID | Amount | customer_id | Age | City | |
|---|---|---|---|---|---|---|
| 0 | 101 | C1 | 250 | C1 | 34.0 | New York |
| 1 | 102 | C2 | 150 | C2 | 45.0 | Los Angeles |
| 2 | 103 | C1 | 300 | C1 | 34.0 | New York |
| 3 | 104 | C3 | 450 | C3 | 28.0 | Chicago |
| 4 | 105 | C3 | 100 | C3 | 28.0 | Chicago |
| 5 | 106 | C4 | 500 | NaN | NaN | NaN |
| 6 | 107 | C2 | 200 | C2 | 45.0 | Los Angeles |