Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - How to Concatenate Two or More Pandas DataFrames along rows?
To concatenate two or more Pandas DataFrames along rows, use the pd.concat() method with axis=0. This combines DataFrames vertically, stacking them on top of each other.
Syntax
pd.concat([df1, df2, df3, ...], axis=0)
Creating Sample DataFrames
First, let's create three sample DataFrames to demonstrate concatenation ?
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])
print("DataFrame1:")
print(dataFrame1)
DataFrame1: Col1 Col2 Col3 0 10 40 70 1 20 50 80 2 30 60 90
import pandas as pd
# Create DataFrame2
dataFrame2 = pd.DataFrame({
"Col1": [100, 110, 120],
"Col2": [130, 140, 150],
"Col3": [160, 170, 180]
}, index=[3, 4, 5])
print("DataFrame2:")
print(dataFrame2)
DataFrame2: Col1 Col2 Col3 3 100 130 160 4 110 140 170 5 120 150 180
import pandas as pd
# Create DataFrame3
dataFrame3 = pd.DataFrame({
"Col1": [200, 210, 220],
"Col2": [230, 240, 250],
"Col3": [260, 270, 280]
}, index=[6, 7, 8])
print("DataFrame3:")
print(dataFrame3)
DataFrame3: Col1 Col2 Col3 6 200 230 260 7 210 240 270 8 220 250 280
Concatenating DataFrames Along Rows
Now let's concatenate all three DataFrames along rows using axis=0 ?
import pandas as pd
# Create three DataFrames
dataFrame1 = pd.DataFrame({
"Col1": [10, 20, 30],
"Col2": [40, 50, 60],
"Col3": [70, 80, 90]
}, index=[0, 1, 2])
dataFrame2 = pd.DataFrame({
"Col1": [100, 110, 120],
"Col2": [130, 140, 150],
"Col3": [160, 170, 180]
}, index=[3, 4, 5])
dataFrame3 = pd.DataFrame({
"Col1": [200, 210, 220],
"Col2": [230, 240, 250],
"Col3": [260, 270, 280]
}, index=[6, 7, 8])
# Concatenate all DataFrames along rows (axis=0)
result = pd.concat([dataFrame1, dataFrame2, dataFrame3], axis=0)
print("Concatenated DataFrame:")
print(result)
Concatenated DataFrame: 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
Key Points
-
axis=0concatenates DataFrames vertically (along rows) - The original index values are preserved in the result
- All DataFrames must have the same column structure
- Pass a list of DataFrames to concatenate multiple DataFrames at once
Conclusion
Use pd.concat() with axis=0 to stack DataFrames vertically along rows. This method preserves the original indices and efficiently combines multiple DataFrames with matching column structures.
Advertisements
