Pandas DataFrame cumsum() Method
In this tutorial, we will learn the Python pandas DataFrame.cumsum()
method. It gives a cumulative sum over a DataFrame or Series axis. It returns a DataFrame or Series of the same size containing the cumulative sum
.
The below shows the syntax of the Python pandas DataFrame.cumsum()
method.
Syntax
DataFrame.cumsum(axis=None, skipna=True, *args, **kwargs)
Parameters
axis: {0 or ‘index’, 1 or ‘columns’}, default 0. The index or the name of the axis. 0 is equivalent to None or ‘index’.
skipna: bool, default True. Exclude NA/null values. If an entire row/column is NA, the result will be NA.
*args, **kwargs: Additional keywords have no effect but might be accepted for compatibility with NumPy.
Example 1: Finding the cumulative sum of the DataFrame
The below example shows how to find the cumulative sum of the DataFrame over the index axis using the DataFrame.cumsum()
method.
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[1, 2, 3, 4], "B":[5, 6, 7, 8]})
print(df)
print("-----------Finding cumulative sum-------")
print(df.cumsum(axis = 0))
Once we run the program we will get the following output.
A B
0 1 5
1 2 6
2 3 7
3 4 8
-----------Finding cumulative sum-------
A B
0 1 5
1 3 11
2 6 18
3 10 26
Example 2: Finding the cumulative sum of the DataFrame
The below example shows how to find the cumulative sum of the DataFrame over the column axis using the DataFrame.cumsum()
method.
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[1, 2, 3, 4], "B":[5, 6, 7, 8]})
print(df)
print("-----------Finding cumulative sum-------")
print(df.cumsum(axis = 1))
Once we run the program we will get the following output.
A B
0 1 5
1 2 6
2 3 7
3 4 8
-----------Finding cumulative sum-------
A B
0 1 6
1 2 8
2 3 10
3 4 12
Example 3: Finding the cumulative sum of the DataFrame
The below example shows how to find the cumulative sum of the DataFrame with null values over the index axis using the DataFrame.cumsum()
method.
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[1, 2, 3, 4], "B":[5, 6, None, 8]})
print(df)
print("-----------Finding cumulative sum-------")
print(df.cumsum(skipna=False))
Once we run the program we will get the following output.
A B
0 1 5.0
1 2 6.0
2 3 NaN
3 4 8.0
-----------Finding cumulative sum-------
A B
0 1 5.0
1 3 11.0
2 6 NaN
3 10 NaN
Conclusion
In this tutorial, we learned the Python pandas DataFrame.cumsum()
method. We learned the syntax, parameters and by solving examples we understood the DataFrame.cumsum()
method.