Home »
Python »
Python Programs
Python - Summing two columns in a pandas dataframe
Given a Pandas DataFrame, we have to sum/add two pandas dataframe columns.
By Pranit Sharma Last updated : September 27, 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.
Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values.
On the other hand, Rows in pandas are the different cell (column) values that are aligned horizontally and also provide uniformity.
Each row can have the same or different value. Rows are generally marked with the index number but in pandas, we can also assign index names according to the needs. In pandas, we can create, read, update, and delete a column or row value.
Problem statement
Given a Pandas DataFrame, we have to sum/add two pandas dataframe columns.
Summing two columns in a pandas dataframe
To sum/add two pandas dataframe columns, we have a very simple approach. We will first create a new column named sum and we will assign the sum of each row to this column.
Let us understand with the help of an example, how to add two DataFrame columns,
Python program for summing two columns in a pandas dataframe
# Importing pandas package
import pandas as pd
# Creating a dictionary
d = {
'One':[1,2,3,4,5],
'Two':[6,7,8,9,10]
}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display Original DataFrame
print("Created DataFrame:\n",df,"\n")
# summing the two columns
df['Sum'] = df['One'] + df['Two']
# Display modified DataFrame
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »