Python - How to Concatenate Two or More Pandas DataFrames along rows?


To concatenate more than two Pandas DataFrames, use the concat() method. Set the axis parameter as axis = 0 to concatenate along rows. At first, import the required library −

import pandas as pd

Let us create the 1st DataFrame −

dataFrame1 = pd.DataFrame(
   {
      "Col1": [10, 20, 30],"Col2": [40, 50, 60],"Col3": [70, 80, 90],
   },
   index=[0, 1, 2],
)

Let us create the 2nd DataFrame −

dataFrame2 = pd.DataFrame(
   {
      "Col1": [100, 110, 120],"Col2": [130, 140, 150],"Col3": [160, 170, 180],
   },
   index=[3, 4, 5],
)

Let us create the 3rd DataFrame −

dataFrame3 = pd.DataFrame(
   {
      "Col1": [200, 210, 220],"Col2": [230, 240, 250],"Col3": [260, 270, 280],
   },
   index=[6, 7, 8],
)

Concatenate all the 3 DataFrames using concat(). Set "axis=1" for concatenation along rows −

res = [dataFrame1, dataFrame2, dataFrame3]
pd.concat(res, axis=1))

Example

Following is the code −

import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Col1": [10, 20, 30],"Col2": [40, 50, 60],"Col3": [70, 80, 90],
   },
   index=[0, 1, 2],
)

# DataFrame1
print"DataFrame1...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Col1": [100, 110, 120],"Col2": [130, 140, 150],"Col3": [160, 170, 180],
   },
   index=[3, 4, 5],
)

# DataFrame2
print"DataFrame2...\n",dataFrame2

dataFrame3 = pd.DataFrame(
   {
      "Col1": [200, 210, 220],"Col2": [230, 240, 250],"Col3": [260, 270, 280],
   },
   index=[6, 7, 8],
)

# DataFrame3
print"DataFrame3...\n",dataFrame3

# concatenating more than 2 dataframes
# set "axis=0" for concatenation along rows
res = [dataFrame1, dataFrame2, dataFrame3]
print"\n Concatenating all the 3 DataFrames (along rows)...\n", pd.concat(res, axis=0)

Output

This will produce the following output −

DataFrame1...
   Col1   Col2   Col3
0   10     40     70
1   20     50     80
2   30     60     90
DataFrame2...
   Col1   Col2   Col3
3  100    130    160
4  110    140    170
5  120    150    180
DataFrame3...
   Col1   Col2   Col3
6   200    230    260
7   210    240    270
8   220    250    280

Concatenating all the 3 DataFrames (along rows)...
   Col1   Col2   Col3
0   10     40     70
1   20     50     80
2   30     60     90
3   100    130    160
4   110    140    170
5   120    150    180
6   200    230    260
7   210    240    270
8   220    250    280

Updated on: 14-Sep-2021

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements