← Back to Pandas Course | Chapter 8: Merging & Joining | Lesson 1 of 7

concat()

concat stacks DataFrames on top of each other or side by side.

In this page:

  1. concat()
Syntax
python
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()

python
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
  1. Duplicate index labels after stacking
  2. Calling concat inside a loop repeatedly
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.