Skip to main content
concatenate-pandas-dataFrames

How To Concatenate Pandas DataFrames

in this pandas tutorials, We’ll learn how to Concatenate two or more Data Frames. The concat() method help to combines Data Frames across rows or columns in pandas.

The Pandas DataFrame is a structure that contains two-dimensional data and its corresponding labels. DataFrames are widely used in data science, machine learning, scientific computing, and many other data-intensive fields.

As we know, The DataFrames are similar to tables or spreadsheets and part of the Python and NumPy ecosystems. The DataFrames are faster, easier to use, and more powerful than tables or spreadsheets.

Pandas concat two dataframes

Let’s concatenate two dataframe using concat() method.

import pandas as pd
import numpy as np

dataframe1 = pd.DataFrame(np.random.randint(100, size=(3, 3)),
                   index=["1", "2", "3"],
                   columns=["eng", "fr", "de"])

dataframe2 = pd.DataFrame(np.random.randint(100, size=(3, 3)),
                   index=["1", "2", "3"],
                   columns=["af", "hi", "ar"])

print(dataframe1);
print(dataframe2);

# concatenating dataframe1 and dataframe2 along columns
horizontal_concat = pd.concat([dataframe1, dataframe2], axis=1)

#Horizontall
display(horizontal_concat)			  

dataframe3 = pd.DataFrame(np.random.randint(100, size=(2, 2)),
                    index=["1", "2"],
                   columns=["eng", "fr"])

dataframe4 = pd.DataFrame(np.random.randint(100, size=(2, 2)),
                   index=["1", "2"],
                   columns=["eng", "fr"])
# concatenating dataframe3 and dataframe4 along rows
vertical_concat = pd.concat([dataframe3, dataframe4], axis=0)


#vertical
display(vertical_concat)

Output:

eng  fr  de
1    3  91  44
2   95  86  26
3   43  40  60

af  hi  ar
1  91   9  21
2   3  44  14
3  10  48  52

Horizontal concatenate

eng  fr  de  af  hi  ar
1   10  71  58  35  73  64
2   46  11  71  27  38  57
3   13  58  15   5  11  67

Vertical concatenate

eng  fr
1   19  30
2   18  70
3   40  95
4   71  87

Step 1: import pandas and NumPy module.
Step 2: define dataframe 1 and dataframe 2.
Step 3: Merging two dataframe(dataframe1, dataframe2) using concat() method.
Step 4: Define dataframe3 and dataframe4.
Step 5: Merging two dataframe(dataframe3, dataframe4) using concat() method.

Leave a Reply

Your email address will not be published. Required fields are marked *