python numpy中cumsum的用法

目录

一、函数作用

二、代码范例

三、结果解释


一、函数作用

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


还比较有意思~

发布了129 篇原创文章 · 获赞 1105 · 访问量 169万+

猜你喜欢

转载自blog.csdn.net/qq_36556893/article/details/101756142
今日推荐