We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Concatenating DataFrames

We've been using pd.merge() to combine related DataFrames by matching keys. By default, pd.concat() solves a different problem: stacking them vertically. Here, we're literally just adding more records to the DataFrame.

Say you have two months of sales data with the same columns:

sales_jan = pd.DataFrame(
    {
        "sale_id": ["K8mQ2xV7", "N4pL9sR2"],
        "month": ["Jan", "Jan"],
        "amount": [100, 150],
    }
)

sales_feb = pd.DataFrame(
    {
        "sale_id": ["B7vD3kT6", "R2cF8nJ5"],
        "month": ["Feb", "Feb"],
        "amount": [200, 125],
    }
)

Concatenate them to create one taller DataFrame:

combined = pd.concat([sales_jan, sales_feb])
print(combined)
#     sale_id  month  amount
# 0  K8mQ2xV7    Jan     100
# 1  N4pL9sR2    Jan     150
# 0  B7vD3kT6    Feb     200
# 1  R2cF8nJ5    Feb     125

Ignore the Index

By default, pd.concat() keeps the original index labels from each DataFrame. That's why the result above has two rows labeled 0 and two rows labeled 1.

That's usually not what you want! Set ignore_index=True to create a fresh sequential index:

combined = pd.concat([sales_jan, sales_feb], ignore_index=True)
print(combined)
#     sale_id  month  amount
# 0  K8mQ2xV7    Jan     100
# 1  N4pL9sR2    Jan     150
# 2  B7vD3kT6    Feb     200
# 3  R2cF8nJ5    Feb     125

Real-world Pandas code is full of df.reset_index(), ignore_index=True on pd.concat(), and similar "index hygiene." This is how analysts work around Pandas' quirky default behavior.

Assignment

Complete the combine_monthly_sales function. It accepts two DataFrames: sales_jan and sales_feb. It should: