Python - Appending two dataframes with same columns, different order

Learn, how can we append two DataFrames with same columns but in different order? By Pranit Sharma Last updated : September 29, 2023

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.

Appending two dataframes with same columns, different order

To append two dataframes with the same columns, different order - means that we are given two DataFrames with the same columns, but the order in which the values of columns in the first DataFrame are arranged is different from the order of values of columns in second DataFrame.

We need to append these two DataFrame without using join and hence in this case, we will append these two DataFrames with the help of df.concat() method, and also, we will pass an index ignore_index = true as a parameter.

The df.concat() is a method of combining or joining two DataFrames, it is a method that appends or inserts one (or more) DataFrame below the other.

Let us understand with the help of an example,

Python program to append two dataframes with same columns, different order

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d = {
    'Name':["Ram","Shyam",'Ghanshyam'],
    'Age':[20,20,21],
    'City':['Bombay','Pune','Nagpur']
}

d2 = {
    'Name':["Shyam","Seeta","Ghanshyam"],
    'Age':[19,20,20],
    'City':['Surat','Kolkata','Bombay']
}

# Creating DataFrames
df = pd.DataFrame(d)
df2 = pd.DataFrame(d2)

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

# Adding two DataFrames
result = pd.concat([df, df2], ignore_index=True)

# display result
print("Result:\n",result)

Output

The output of the above program is:

Example: Appending two dataframes with same columns, different order

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.