TExcelTAD
Home › pandas › Concatenating DataFrames

Concatenating DataFrames

Where merge joins tables side by side by matching keys, pd.concat() simply stacks them: one month's data under the previous month's, or extra columns glued on the right. It's the tool for combining files with the same layout.

Stacking rows

python · try it yourself
import pandas as pd

jan = pd.DataFrame({"product": ["mug", "cap"], "units": [30, 12]})
feb = pd.DataFrame({"product": ["mug", "bag"], "units": [24, 9]})
mar = pd.DataFrame({"product": ["cap", "bag"], "units": [15, 11]})

all_months = pd.concat([jan, feb, mar])
print(all_months)
  product  units
0     mug     30
1     cap     12
0     mug     24
1     bag      9
0     cap     15
1     bag     11

concat takes a list of DataFrames. Notice the index: each piece kept its own 0, 1, so labels now repeat.

Fixing the index

Use ignore_index=True for a fresh 0…n−1 index, or keys= to label where each piece came from:

python · try it yourself
import pandas as pd

jan = pd.DataFrame({"product": ["mug", "cap"], "units": [30, 12]})
feb = pd.DataFrame({"product": ["mug", "bag"], "units": [24, 9]})

print(pd.concat([jan, feb], ignore_index=True))

labelled = pd.concat([jan, feb], keys=["Jan", "Feb"])
print(labelled)
print(labelled.loc["Feb"])
  product  units
0     mug     30
1     cap     12
2     mug     24
3     bag      9
      product  units
Jan 0     mug     30
    1     cap     12
Feb 0     mug     24
    1     bag      9
  product  units
0     mug     24
1     bag      9

With keys, the result has a two-level index (a MultiIndex), and loc["Feb"] retrieves one piece. Often it's even more useful to turn the label into a normal column:

python · try it yourself
import pandas as pd

jan = pd.DataFrame({"product": ["mug", "cap"], "units": [30, 12]})
feb = pd.DataFrame({"product": ["mug", "bag"], "units": [24, 9]})

frames = {"2024-01": jan, "2024-02": feb}
combined = pd.concat([df.assign(month=m) for m, df in frames.items()], ignore_index=True)
print(combined)
print(combined.groupby("product")["units"].sum())
  product  units    month
0     mug     30  2024-01
1     cap     12  2024-01
2     mug     24  2024-02
3     bag      9  2024-02
product
bag     9
cap    12
mug    54
Name: units, dtype: int64

This pattern (load each file, tag it, concat) is how you combine a folder of monthly exports.

Different columns

Columns are matched by name. A column missing in one piece is filled with NaN. join="inner" keeps only the columns all pieces share:

python · try it yourself
import pandas as pd

old = pd.DataFrame({"id": [1, 2], "email": ["a@x.io", "b@x.io"]})
new = pd.DataFrame({"id": [3], "email": ["c@x.io"], "phone": ["555-0102"]})

print(pd.concat([old, new], ignore_index=True))
print(pd.concat([old, new], ignore_index=True, join="inner"))
   id   email     phone
0   1  a@x.io       NaN
1   2  b@x.io       NaN
2   3  c@x.io  555-0102
   id   email
0   1  a@x.io
1   2  b@x.io
2   3  c@x.io

Side by side: axis=1

With axis=1, concat places frames next to each other, aligning rows by index:

python · try it yourself
import pandas as pd

heights = pd.Series([1.62, 1.80, 1.75], index=["Uma", "Vic", "Wes"], name="height_m")
weights = pd.Series([58, 81, 70], index=["Vic", "Uma", "Wes"], name="weight_kg")
body = pd.concat([heights, weights], axis=1)
body["bmi"] = (body["weight_kg"] / body["height_m"] ** 2).round(1)
print(body)
     height_m  weight_kg   bmi
Uma      1.62         81  30.9
Vic      1.80         58  17.9
Wes      1.75         70  22.9

Although weights listed the names in another order, the values landed next to the right people, because alignment uses the index labels.

Adding a single row

There's no append method any more (it was removed in pandas 2.0). To add rows, concat a small DataFrame:

python · try it yourself
import pandas as pd

stock = pd.DataFrame({"item": ["pen", "ink"], "qty": [40, 8]})
new_row = pd.DataFrame([{"item": "pad", "qty": 15}])
stock = pd.concat([stock, new_row], ignore_index=True)
print(stock)
  item  qty
0  pen   40
1  ink    8
2  pad   15

Tip: Don't grow a DataFrame row by row inside a loop; each concat copies everything. Collect rows in a Python list and build the DataFrame once at the end: pd.DataFrame(list_of_dicts).

Test yourself

What does pd.concat([a, b]) do by default?

  1. Joins a and b on matching keys
  2. Stacks the rows of b under a
  3. Puts b to the right of a
  4. Adds the values together

How do you get a clean 0, 1, 2… index after concatenating?

  1. sort=True
  2. ignore_index=True
  3. reset=True
  4. keys=None

One frame has a column phone that the other lacks. What appears in it for rows from the other frame?

  1. An error is raised
  2. Empty strings
  3. NaN
  4. The column is dropped