Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - How to Concatenate Two or More Pandas DataFrames along columns?\\n
To concatenate more than two Pandas DataFrames, use the concat() method. Set the axis parameter as axis = 1 to concatenate along columns. 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() and set “axis=1” to concatenate along columns −
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 3 dataframes
# set "axis=1" for concatenation along columns
res = [dataFrame1, dataFrame2, dataFrame3]
print"\n Concatenating all the 3 DataFrames (along columns)...\n", pd.concat(res, axis=1)
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 columns)... Col1 Col2 Col3 Col1 Col2 Col3 Col1 Col2 Col3 0 10.0 40.0 70.0 NaN NaN NaN NaN NaN NaN 1 20.0 50.0 80.0 NaN NaN NaN NaN NaN NaN 2 30.0 60.0 90.0 NaN NaN NaN NaN NaN NaN 3 NaN NaN NaN 100.0 130.0 160.0 NaN NaN NaN 4 NaN NaN NaN 110.0 140.0 170.0 NaN NaN NaN 5 NaN NaN NaN 120.0 150.0 180.0 NaN NaN NaN 6 NaN NaN NaN NaN NaN NaN 200.0 230.0 260.0 7 NaN NaN NaN NaN NaN NaN 210.0 240.0 270.0 8 NaN NaN NaN NaN NaN NaN 220.0 250.0 280.0
Advertisements