Stacking Tables with concat

Two tables of the same shape, one after the other.

Rows end to end

concat stacks tables that share their columns. ignore_index renumbers the result, which you almost always want after stacking.

import pandas as pd

jan = pd.DataFrame({"name": ["Ada"], "score": [92]})
feb = pd.DataFrame({"name": ["Grace"], "score": [88]})
both = pd.concat([jan, feb], ignore_index=True)
print(both.shape)

Columns that do not line up

A column missing from one side is not an error. It appears with a gap for the rows that never had it, which is honest and occasionally a surprise.

import pandas as pd

a = pd.DataFrame({"x": [1]})
b = pd.DataFrame({"x": [2], "y": [3]})
out = pd.concat([a, b], ignore_index=True)
print(sorted(out.columns), int(out["y"].isna().sum()))

Exercise

Try It Yourself

Write stack(tables) that stacks a list of tables into one with a fresh index, and returns the number of rows.

Press Run to see output

Check Your Understanding