这里简单地介绍一下numpy
模块中地accumulate()
函数的用法。
代码如下:
# -*- coding: utf-8 -*-
import numpy as np
class Debug:
def __init__(self):
self.array1 = np.array([1, 2, 3, 4])
self.array3 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
def mainProgram(self):
result = np.add.accumulate(self.array1)
print("The value of result is: ")
print(result)
result1 = np.add.accumulate(self.array3, axis=0)
print("The value of result1 is: ")
print(result1)
result2 = np.add.accumulate(self.array3, axis=1)
print("The value of result2 is: ")
print(result2)
if __name__ == '__main__':
main = Debug()
main.mainProgram()
"""
The value of result is:
[1 3 6 10]
The value of result1 is:
[[1 2 3 4]
[6 8 10 12]]
The value of result2 is:
[[1 3 6 10]
[5 11 18 26]]
"""
我们可以看到,accumulate()
函数是一个累计起来的运算,当它作用在 add()
函数上时,就是一个累加运算,self.array1
的值为 [1, 2, 3, 4]
,当我们进行累加后得到 [1 3 6 10]
,我们可以看到,第二个值 3=1+2
,第三个值 6=1+2+3
,第四个值 10=1+2+3+4
。从 result1
的结果和 result2
的结果,我们可以看出,当指定 axis=0
时是沿着 y
轴进行累加,指定 axis=1
时是沿着 x
轴进行累加,具体为什么这样,可以参考np.repeat()的坐标轴问题。
如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~