concat()
concat stacks DataFrames on top of each other or side by side.
In this page:
Syntax
pd.concat([df1, df2])
pd.concat([df1, df2], axis=1)
concat()
pd.concat([df1, df2]) appends rows (axis=0), and axis=1 places them side by side aligned on the index. ignore_index=True rebuilds a clean index. Use keys to label the source of each block.
Note:
concat in a loop is slow; collect DataFrames in a list and call concat once.
Example: concat()
import pandas as pd
a = pd.DataFrame({"id": [1, 2], "v": ["x", "y"]})
b = pd.DataFrame({"id": [3], "v": ["z"]})
print(pd.concat([a, b], ignore_index=True))
print(pd.concat([a, b], keys=["first", "second"]))
# Output:
# id v
# 0 1 x
# 1 2 y
# 2 3 z
# id v
# first 0 1 x
# 1 2 y
# second 0 3 z
Related Topics
Common Mistakes
- Duplicate index labels after stacking
- Calling concat inside a loop repeatedly
- Mismatched columns creating NaN
Chapter Summary
- axis=0 stacks rows
- axis=1 joins columns
- ignore_index renumbers
- Mismatched columns become NaN
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: