numpy cumsum 用法及代码示例

用法:
numpy.cumsum(a, axis=None, dtype=None, out=None)
返回沿给定轴的元素的累加和。

描述
参数 a: : array_like

输入数组。
axis: : int, 可选参数

计算累计和的轴。默认值(无)是计算展平数组上的总和。
dtype: : dtype, 可选参数

返回的数组的类型和元素在其中累加的累加器的类型。如果dtype未指定,则默认为a的dtype,除非a的整数dtype的精度小于默认平台整数的精度。在这种情况下,将使用默认平台整数。
out: : ndarray, 可选参数

放置结果的备用输出数组。它必须具有与预期输出相同的形状和缓冲区长度,但是如果需要,将强制转换类型。看到doc.ufuncs(第“Output arguments”节)了解更多详情。

返回值 cumsum_along_axis: : ndarray。

除非指定out,否则将返回保存结果的新数组,在这种情况下,将返回对out的引用。结果具有与a相同的大小,并且与if轴不为None或a为一维数组的形状相同。

注意:

使用整数类型时,算术是模块化的,并且在溢出时不会引发错误。

例子:

>>> a = np.array([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.cumsum(a)
array([ 1,  3,  6, 10, 15, 21])
>>> np.cumsum(a, dtype=float)     # specifies type of output value(s)
array([  1.,   3.,   6.,  10.,  15.,  21.])
>>> np.cumsum(a,axis=0)      # sum over rows for each of the 3 columns
array([[1, 2, 3],
       [5, 7, 9]])
>>> np.cumsum(a,axis=1)      # sum over columns for each of the 2 rows
array([[ 1,  3,  6],
       [ 4,  9, 15]])

发表回复

登录... 后才能评论