← Data analysis with Python

Stacking tables with concat

Put tables with the same columns on top of each other.

Start this lesson

Data often arrives in pieces: one table per month, one per store, one per school. When the pieces have the same columns, pd.concat([a, b]) stacks them into one long table so you can analyze them together. Add ignore_index=True so the new table gets fresh row labels 0, 1, 2, ... instead of repeating the old ones. It often helps to add a column first that says where each piece came from.

import pandas as pd

jan = pd.DataFrame({"store": ["North", "South"], "units": [310, 280]})
feb = pd.DataFrame({"store": ["North", "South"], "units": [295, 330]})
jan["month"] = "Jan"
feb["month"] = "Feb"
both = pd.concat([jan, feb], ignore_index=True)
print(both)
print(both.groupby("store")["units"].sum())

The month column remembers where each row came from. After stacking there are 4 rows, and groupby can total each store across both months.

If the column names do not match exactly, concat makes separate columns and fills the gaps with NaN. Check df.columns on both pieces first.