Stack two pandas dataframes

Given two pandas dataframes, we have to stack them.
Submitted by Pranit Sharma, on November 23, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Stack two dataframes

For this purpose, we will use the pandas.concat() method inside which we will pass both the dataframes and a parameter (ignore_index=True).

We could have used the pandas.merge() method but the reason we are using pandas.concat() method is that the concat method is used to combine dataframes in such a way that it appends or inserts one (or more) dataframes below the other.

Let us understand with the help of an example,

Python program to stack two pandas dataframes

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating dataframes
df1 = pd.DataFrame(data=np.random.randint(0,50,(2,5)),columns=list('12345'))
df2 = pd.DataFrame(data=np.random.randint(0,50,(2,5)),columns=list('12345'))

# Display original DataFrames
print("Original DataFrame 1:\n",df1,"\n")
print("Original DataFrame 2:\n",df2,"\n")

# Stacking two dataframes
res = pd.concat([df1,df2],ignore_index=True)

# Display Result
print('New DataFrame:\n',res)


The output of the above program is:

Example: Stack two pandas dataframes

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.