Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Series.cumsum() function

Pandas Series.cumsum() function

Pandas Common Functions Common Pandas functions


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


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

]

)

print

(

"Daily sales (yuan):"

)

print

(

daily_sales

)

print

(

)

Compute cumulative sales

cumulative_sales

=

daily_sales.

cumsum

(

)

print

(

"Cumulative sales (yuan):"

)

print

(

cumulative_sales

)

print

(

)

print

(

"Analysis:"

)

print

(

"- Day 1 cumulative: 1000"

)

print

(

"- Day 2 cumulative: 1000 + 1500 = 2500"

)

print

(

"- Day 3 cumulative: 1000 + 1500 + 1200 = 3700"

)

print

(

"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:

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

]

)

print

(

"Raw data (with missing values):"

)

print

(

data_with_nan

)

print

(

)

By default skipna=True, skipping NaN when computing the cumulative sum

cumulative_skipna

=

data_with_nan.

cumsum

(

)

print

(

"Cumulative sum with skipna=True (default):"

)

print

(

cumulative_skipna

)

print

(

)

Set skipna=False, and NaN positions interrupt the accumulation

cumulative_no_skipna

=

data_with_nan.

cumsum

(

skipna

=

False

)

print

(

"Cumulative sum with skipna=False:"

)

print

(

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:

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

(

)

iloc

[

0

]

len

(

stock_prices

)

Or more simply, use cumsum to compute the cumulative change relative to the initial price

print

(

"Stock price data:"

)

print

(

stock_prices.

values

)

print

(

)

Compute the price change for the day (compared with the previous day)

print

(

"Daily price changes:"

)

print

(

daily_change.

fillna

(

0

)

.

values

)

print

(

)

Another approach: computing cumulative returns

cumulative_return

=

(

(

stock_prices / stock_prices.

iloc

[

0

]

)

1

)

100

print

(

"Cumulative return (%):"

)

print

(

cumulative_return.

values

)

print

(

)

Cumulative value starting from 100 yuan

initial_price

=

100

cumulative_value

=

initial_price + stock_prices.

cumsum

(

)

iloc

[

0

]

print

(

"Cumulative value (assuming an initial 100 yuan):"

)

print

(

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

}

)

print

(

"Monthly sales (yuan):"

)

print

(

monthly_sales

)

print

(

)

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

)

}

)

print

(

"Sales summary table:"

)

print

(

summary

)

print

(

)

print

(

f

"Cumulative sales for the first half: {cumulative_sales.iloc[-1]} yuan"

)

print

(

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'

]

)

print

(

"Monthly sales data:"

)

print

(

sales_data

)

print

(

)

Compute cumulative sales by column (default)

cumulative_by_col

=

sales_data.

cumsum

(

)

print

(

"Cumulative sales by product:"

)

print

(

cumulative_by_col

)

print

(

)

Compute cumulative sales by row

cumulative_by_row

=

sales_data.

cumsum

(

axis

=

1

)

print

(

"Cumulative sales by month:"

)

print

(

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:


Notes


Summary

Series.cumsum() is a fundamental function in time series analysis. Its main features include:

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.

Pandas Common Functions Common Pandas functions