Home »
Python »
Python Programs
Cumsum as a new column in an existing Pandas dataframe
Learn, how to find the cumsum as a new column in existing Pandas dataframe?
By Pranit Sharma Last updated : October 06, 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.
The cumulative can be defined as a sum of a given sequence that is increasing or getting bigger with more additions. A real example of a cumulative sum is the increasing amount of water in a swing pool. It can be understood as a list whose ith element is the sum of the (i + 1) elements.
Problem statement
Suppose we are given the Pandas dataframe with some columns and we need to find the cumulative sum of a particular column and add it as a new column to the same dataframe.
Finding the cumsum as a new column in existing dataframe
For this purpose, we will simply use the cumsum() method on that particular column. This method returns the cumulative sum of the elements along a given axis.
Let us understand with the help of an example,
Python program to find the cumsum as a new column in existing Pandas dataframe
# Importing pandas
import pandas as pd
# Import numpy
import numpy as np
# Creating a dataframe
df = pd.DataFrame({
'A':[50244,6042343,70234,4245],
'B':[34534,5356,56445,1423],
'C':[46742,685,4563,7563]
})
# Display original DataFrame
print("Original DataFrame:\n",df,"\n")
# Finding cumsum of C
df['Cumsum_of_c'] = df['C'].cumsum()
# Display result
print("Result:\n",df)
Output
The output of the above program is:
Python Pandas Programs »