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 code 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)

Output:

Example: Stack two pandas dataframes

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.