Pandas combining two dataframes horizontally

Given two pandas dataframes, we have to combine them horizontally. By Pranit Sharma Last updated : October 03, 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.

Problem statement

We are given two pandas DataFrames with different columns. We want to combine them together horizontally.

Combining two pandas dataframes horizontally

For this purpose, we will use concat method of pandas which will allow us to combine these two DataFrames. The concat() is the method of combining or joining two DataFrames. The concat() is used to combine DataFrames but 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 combine two dataframes horizontally

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {
    'A': [1,2,3,4,5],
    'B': [1,2,3,4,5]

d2 = {
    'C': [1,2,3,4,5],
    'D': [1,2,3,4,5]

# Creating two DataFrames
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

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

# Combining two dataframes
res = pd.concat([df1, df2], axis=1)

# Display result


The output of the above program is:

Example: Python - Pandas combining two dataframes horizontally

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.