Pandas DataFrame merge summing column

Learn, how can we merge summed columns in pandas dataframe?
Submitted by Pranit Sharma, on October 09, 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.

Problem statement

Suppose we are given two DataFrames both with two fields, name, and height. We need to sum Height values during merging for similar values in the common column.

Merging summing column

For this purpose, we will use the concat() method, and then we will apply the sum method for merging all the summed values. 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 merge summed columns

# Importing pandas package
import pandas as pd

# Creating dictionaries
d1 = {

d2 = {

# Creating 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")

# Merging summed values
res = pd.concat([df1, df2]).groupby(['name', 'height']).sum().reset_index()

# Display result


The output of the above program is:

Example: Pandas DataFrame merge summing column

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.