Pandas Series.cumsum() function
Series.cumsum() is a Pandas function for computing the cumulative sum of a Series. A cumulative sum means that starting from the first element, the value at each position equals the sum of all elements up to and including that position.
Cumulative sums are frequently used in financial data analysis (e.g., computing cumulative returns), sales analysis (e.g., computing cumulative sales), time series analysis, and other scenarios.
Basic syntax and parameters
cumsum() is a member function of the Series object and is called directly with the dot operator.
Syntax format
Series.cumsum(axis=None, skipna=True, dtype=None, out=None, **kwargs)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| axis | int | Specify the axis; a Series has only one column, so this parameter exists mainly for compatibility with DataFrame. | None |
| skipna | bool | If True, skip NaN values during computation; if False, encountering a NaN interrupts the accumulation. | True |
| dtype | dtype | Specify the output data type. | None |
| out | ndarray | An array for storing the result; usually it does not need to be set. | None |
Return Value
- Return Type:
Series - Description: Returns a new Series in which the value at each position is the cumulative sum.
Example
Let us thoroughly master Series.cumsum() through a series of examples from simple to complex.
Example 1: Basic usage - computing cumulative sales
A cumulative sum is the total of all values up to the current position.
Example
import
pandas
as
pd
Create a Series containing daily sales
daily_sales
=
pd.
Series
(
[
1000
,
1500
,
1200
,
1800
,
2000
,
900
,
1600
]
)
(
"Daily sales (yuan):"
)
(
daily_sales
)
(
)
Compute cumulative sales
cumulative_sales
=
daily_sales.
cumsum
(
)
(
"Cumulative sales (yuan):"
)
(
cumulative_sales
)
(
)
(
"Analysis:"
)
(
"- Day 1 cumulative: 1000"
)
(
"- Day 2 cumulative: 1000 + 1500 = 2500"
)
(
"- Day 3 cumulative: 1000 + 1500 + 1200 = 3700"
)
(
"And so on..."
)
Running result:
每日销售额(元):
0 1000
1 1500
2 1200
3 1800
4 2000
5 900
6 1600
dtype: int64
累计销售额(元):
0 1000
1 2500
2 3700
3 5500
4 7500
5 8400
6 10000
dtype: int64
分析:
- 第1天的累计销售就是当天的销售额
- 第2天的累计销售额 = 第1天 + 第2天的销售额
- 以此类推...
Code analysis:
- Cumulative sum at position 1 = 1000
- Cumulative sum at position 2 = 1000 + 1500 = 2500
- Cumulative sum at position 3 = 1000 + 1500 + 1200 = 3700
- And so on...
Example 2: Working with data that contains missing values
skipna parameter determines how missing values are handled.
Example
import
pandas
as
pd
import
numpy
as
np
Create a Series containing missing values
data_with_nan
=
pd.
Series
(
[
10
,
20
,
np.
nan
,
30
,
40
]
)
(
"Raw data (with missing values):"
)
(
data_with_nan
)
(
)
By default skipna=True, skipping NaN when computing the cumulative sum
cumulative_skipna
=
data_with_nan.
cumsum
(
)
(
"Cumulative sum with skipna=True (default):"
)
(
cumulative_skipna
)
(
)
Set skipna=False, and NaN positions interrupt the accumulation
cumulative_no_skipna
=
data_with_nan.
cumsum
(
skipna
=
False
)
(
"Cumulative sum with skipna=False:"
)
(
cumulative_no_skipna
)
Running result:
原始数据(含缺失值):
0 10.0
1 20.0
2 NaN
3 30.0
4 40.0
dtype: float64
Cumulative sum with skipna=True (default):
0 10.0
1 30.0
2 NaN
3 60.0
4 100.0
dtype: float64
Cumulative sum with skipna=False:
0 10.0
1 30.0
2 NaN
3 NaN
4 DataFrame
Code analysis:
- When
skipna=True, NaN positions are skipped and subsequent accumulation continues based on the valid values. - Calculation: 10 -> 30 -> (skipped) -> 60 -> 100
- When
skipna=False, all positions after a NaN become NaN.
Example 3: Analyzing alongside the original data
In real analysis, you usually need to look at the original and cumulative data together.
Example
import
pandas
as
pd
Create stock price data
stock_prices
=
pd.
Series
(
[
100
,
102
,
98
,
105
,
103
,
108
,
110
]
)
Compute daily price changes
daily_change
=
stock_prices.
diff
(
)
Compute cumulative price changes
cumulative_change
=
stock_prices.
cumsum
(
)
- stock_prices.
iloc
[
0
]
len
(
stock_prices
)
- stock_prices
Or more simply, use cumsum to compute the cumulative change relative to the initial price
(
"Stock price data:"
)
(
stock_prices.
values
)
(
)
Compute the price change for the day (compared with the previous day)
(
"Daily price changes:"
)
(
daily_change.
fillna
(
0
)
.
values
)
(
)
Another approach: computing cumulative returns
cumulative_return
=
(
(
stock_prices / stock_prices.
iloc
[
0
]
)
1
)
100
(
"Cumulative return (%):"
)
(
cumulative_return.
values
)
(
)
Cumulative value starting from 100 yuan
initial_price
=
100
cumulative_value
=
initial_price + stock_prices.
cumsum
(
)
- stock_prices.
iloc
[
0
]
(
"Cumulative value (assuming an initial 100 yuan):"
)
(
cumulative_value.
values
)
Running result:
股价数据:[100, 102, 98, 105, 103, 108, 110]
每日涨跌(与前一天相比):
[ 0., 2., -4., 7., -2., 5., 2.]
累计收益(%):
[0.0, 2.0, -2.0, 5.0, 3.0, 8.0, 10.0]
累计价值(假设初始 100 元):
0 100
1 202
2 300
3 405
4 508
5 616
6 726
dtype: int64
分析:第 7 天时,股价从 100 涨到 110,累计收益率为 10%。
Example 4: Real-world application - monthly cumulative data
Demonstrate a typical use of cumsum in financial analysis.
Example
import
pandas
as
pd
Create monthly sales data
monthly_sales
=
pd.
Series
(
{
'Jan'
:
50000
,
'Feb'
:
62000
,
'Mar'
:
58000
,
'Apr'
:
70000
,
'May'
:
75000
,
'Jun'
:
80000
}
)
(
"Monthly sales (yuan):"
)
(
monthly_sales
)
(
)
Compute monthly cumulative sales
cumulative_sales
=
monthly_sales.
cumsum
(
)
Create a summary table
summary
=
pd.
DataFrame
(
{
'Monthly sales'
: monthly_sales
,
'Cumulative sales'
: cumulative_sales
,
'Annual target completion ratio'
:
(
cumulative_sales /
500000
100
)
.
round
(
1
)
}
)
(
"Sales summary table:"
)
(
summary
)
(
)
(
f
"Cumulative sales for the first half: {cumulative_sales.iloc[-1]} yuan"
)
(
f
"Annual target completion rate: {cumulative_sales.iloc[-1]/500000*100:.1f}%"
)
Running result:
月度销售额(元):
1月 50000
2月 62000
累计 112000
4月 70000
5月 75000
6月 80000
dtype: int64
Sales Summary Table:
月度销售额 累计销售额 完成年度目标(%)
1月 50000 50000 10.0
2月 62000 112000 22.4
3月 58000 170000 34.0
4月 70000 240000 累计 34.0%
5月 75000 315000 63.0
6月 累计 395000 79.0
dtype: int64
分析:6 月底累计销售额为 39.5 万元,已完成年度目标的 79.0%。
Example 5: Applying cumsum in a DataFrame
cumsum can also be used by column or by row in a DataFrame.
Example
import
pandas
as
pd
Create a DataFrame containing sales of multiple products
sales_data
=
pd.
DataFrame
(
{
'Product A'
:
[
100
,
150
,
120
,
180
]
,
'Product B'
:
[
80
,
90
,
110
,
130
]
,
'Product C'
:
[
50
,
60
,
70
,
80
]
}
,
index
=
[
'Jan'
,
'Feb'
,
'Mar'
,
'Apr'
]
)
(
"Monthly sales data:"
)
(
sales_data
)
(
)
Compute cumulative sales by column (default)
cumulative_by_col
=
sales_data.
cumsum
(
)
(
"Cumulative sales by product:"
)
(
cumulative_by_col
)
(
)
Compute cumulative sales by row
cumulative_by_row
=
sales_data.
cumsum
(
axis
=
1
)
(
"Cumulative sales by month:"
)
(
cumulative_by_row
)
Running result:
Monthly sales data:
产品A 产品B 产品C
1月 100 80 50
2月 150 90 60
3月 120
4月 180 130 80
By cumulative product sales:
产品A 产品B 产品C
1月 100 80 50
2月 250 170 110
3月 370 280 180
4月 550 410 260
Cumulative sales by month:
产品A 产品B 产品C
1月 100.0 180.0 230.0
2月 250.0 340.0 400.0
Code analysis:
- Default
axis=0, compute the cumulative sum along columns. - Settings
axis=1, compute the cumulative sum along rows.
Notes
- cumsum returns a new Series and does not modify the original data.
- By default skipna=True, so NaN values are skipped.
- When skipna=False, encountering a NaN causes all subsequent values to become NaN.
- In a DataFrame, the axis parameter can control the direction of accumulation.
- The computation of cumulative sums is order-dependent and cannot be parallelized.
Summary
Series.cumsum() is a fundamental function in time series analysis. Its main features include:
- Compute cumulative values from the start to the current position.
- Supports handling missing values, controlled via the skipna parameter.
- In a DataFrame, supports computation by row or by column.
- Widely used in financial analysis, sales statistics, progress tracking, and other scenarios.
Cumulative sums help us understand how data changes over time and are an important tool in data analysis. Used together with other cumulative functions such as cumprod, cummax, and cummin, they provide more comprehensive insights into the data.
Common Pandas functions