Combining DataFrames helps you join different pieces of data together. This lets you see the full picture and find useful insights.
Why combining DataFrames matters in Pandas
Introduction
Syntax
Pandas
pd.concat([df1, df2], axis=0) pd.merge(df1, df2, on='key')
pd.concat stacks DataFrames either vertically (rows) or horizontally (columns).
pd.merge joins DataFrames based on matching column values, like a database join.
Examples
Pandas
import pandas as pd df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]}) result = pd.concat([df1, df2], axis=0) print(result)
Pandas
import pandas as pd df1 = pd.DataFrame({'key': ['K0', 'K1'], 'A': [1, 2]}) df2 = pd.DataFrame({'key': ['K0', 'K1'], 'B': [3, 4]}) result = pd.merge(df1, df2, on='key') print(result)
Sample Program
This example stacks January and February sales data into one DataFrame to see total sales over two months.
Pandas
import pandas as pd # Sales data for January jan_sales = pd.DataFrame({ 'Product': ['Apple', 'Banana'], 'Sales': [100, 150] }) # Sales data for February feb_sales = pd.DataFrame({ 'Product': ['Apple', 'Banana'], 'Sales': [120, 130] }) # Combine sales data for both months all_sales = pd.concat([jan_sales, feb_sales], axis=0, ignore_index=True) print(all_sales)
Important Notes
Use ignore_index=True in pd.concat to reset row numbers after combining.
When merging, make sure the key columns have matching names and data types.
Combining data helps avoid working with many small files separately.
Summary
Combining DataFrames lets you join or stack data to get a complete view.
Use pd.concat to stack rows or columns.
Use pd.merge to join DataFrames based on matching columns.
Practice
1. Why do we combine DataFrames in pandas?
pd.concat and pd.merge are common methods. What is the main reason to combine DataFrames?easy
Solution
Step 1: Understand the purpose of combining DataFrames
Combining DataFrames helps to bring together data from different sources or parts to analyze them as one.Step 2: Identify the main reason
Usingpd.concatstacks data vertically or horizontally, andpd.mergejoins data based on matching columns, both to get a fuller dataset.Final Answer:
To get a complete view by joining or stacking data -> Option AQuick Check:
Combining DataFrames = Complete view [OK]
Hint: Combining means joining or stacking data for full info [OK]
Common Mistakes:
- Thinking combining deletes duplicates automatically
- Confusing combining with data type changes
- Believing combining converts DataFrames to lists
2. Which of the following is the correct syntax to stack two DataFrames
df1 and df2 vertically using pandas?easy
Solution
Step 1: Recall the function to stack DataFrames vertically
pd.concatstacks DataFrames; axis=0 means stacking rows vertically.Step 2: Check the syntax
The correct syntax ispd.concat([df1, df2], axis=0). Other options misusepd.mergeor wrong axis or argument types.Final Answer:
pd.concat([df1, df2], axis=0) -> Option BQuick Check:
Stack vertically = concat with axis=0 [OK]
Hint: Use pd.concat with a list and axis=0 to stack rows [OK]
Common Mistakes:
- Using pd.merge instead of pd.concat for stacking
- Passing DataFrames without a list to pd.concat
- Using wrong axis value for vertical stacking
3. What will be the output of this code?
import pandas as pd
df1 = pd.DataFrame({'key': ['A', 'B'], 'val1': [1, 2]})
df2 = pd.DataFrame({'key': ['B', 'C'], 'val2': [3, 4]})
result = pd.merge(df1, df2, on='key', how='inner')
print(result)medium
Solution
Step 1: Understand pd.merge with how='inner'
Inner join keeps only rows with keys present in both DataFrames. Here keys are 'A', 'B' in df1 and 'B', 'C' in df2.Step 2: Find common keys and merge rows
Only 'B' is common. So result has one row with key 'B', val1=2 from df1, val2=3 from df2.Final Answer:
key val1 val2 0 B 2 3 -> Option DQuick Check:
Inner join = common keys only [OK]
Hint: Inner merge keeps only matching keys in both DataFrames [OK]
Common Mistakes:
- Expecting all keys from both DataFrames (confusing with outer join)
- Mixing up val2 values for keys
- Ignoring how='inner' effect
4. The following code throws an error. What is the main issue?
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2]})
df2 = pd.DataFrame({'B': [3, 4]})
result = pd.merge(df1, df2, on='A')
print(result)medium
Solution
Step 1: Check columns in both DataFrames
df1 has column 'A', but df2 has only column 'B'. So 'A' is missing in df2.Step 2: Understand pd.merge on parameter
pd.merge requires the 'on' column to be present in both DataFrames to join on it. Missing column causes error.Final Answer:
Column 'A' does not exist in both DataFrames -> Option AQuick Check:
Merge 'on' column must be in both DataFrames [OK]
Hint: Merge 'on' column must exist in both DataFrames [OK]
Common Mistakes:
- Thinking axis parameter is needed for merge
- Believing DataFrames must have same row count
- Assuming merge works with different columns without 'on'
5. You have two DataFrames:
You want a DataFrame that includes all ids from both, with scores and grades matched where possible, and NaN where missing. Which code achieves this?
df1 = pd.DataFrame({'id': [1, 2, 3], 'score': [90, 80, 70]})
df2 = pd.DataFrame({'id': [2, 3, 4], 'grade': ['B', 'C', 'A']})You want a DataFrame that includes all ids from both, with scores and grades matched where possible, and NaN where missing. Which code achieves this?
hard
Solution
Step 1: Understand the goal
We want all ids from both DataFrames, matching scores and grades where ids overlap, and NaN where data is missing.Step 2: Choose the correct merge type
Usinghow='outer'inpd.mergekeeps all keys from both DataFrames, filling missing values with NaN.Step 3: Check other options
pd.concatstacks data but does not join on keys;how='inner'drops ids not in both.Final Answer:
pd.merge(df1, df2, on='id', how='outer') -> Option CQuick Check:
Outer merge = all keys, fill missing with NaN [OK]
Hint: Use outer merge to keep all keys and fill missing data [OK]
Common Mistakes:
- Using inner merge and losing unmatched ids
- Using concat which stacks instead of joining
- Confusing axis parameter with merge how
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
