目錄
一、函數作用
1.該函數定義在multiarray.py中有定義
def cumsum(self, axis=None, dtype=None, out=None): # real signature unknown; restored from __doc__
"""
a.cumsum(axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along the given axis.
Refer to `numpy.cumsum` for full documentation.
See Also
--------
numpy.cumsum : equivalent function
"""
pass
作用是:返回給定軸上元素的累積和。
二、代碼範例
說的有些抽象,接下來還是博主帶領大家寫個例子:
import numpy as np
a = np.asarray([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
b = a.cumsum(axis=0)
print(b)
c = a.cumsum(axis=1)
print(c)
定義一個numpy矩陣a,3x3:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
運行結果:
b爲:
[[ 1 2 3]
[ 5 7 9]
[12 15 18]]
c爲:
[[ 1 3 6]
[ 4 9 15]
[ 7 15 24]]
三、結果解釋
1.參數axis=0指的是按行累加,即本行=本行+上一行,b的由來:
第二行:[5 7 9]
其中1 2 3是第一行累加之後的結果(因爲第一行沒有前一行,所以可以理解爲 + 0)
5 = 1 + 4
7 = 2 + 5
9 = 3 + 6
第三行:[12 15 18]
其中5 7 9是第二行累加之後的結果
12 = 5 + 7 = 1 + 4 + 7
15 = 7 + 8 = 2 + 5 + 8
18 = 9 + 9 = 3 + 6 + 9
所以最終是:
1 2 3
5 7 9
12 15 18
2.參數axis=1指的是按列相加,即本列=本列+上一列
同樣的道理:
第二列:
3 = 1 + 2
9 = 4 + 5
15 = 7 + 8
第三列:
6 = 3 + 3 = 1 + 2 + 3
15 = 9 + 6 = 4 + 5 + 6
24 = 15 + 9 = 7 + 8 + 9
還比較有意思~