Python中的numpy.cumsum()

Python numpy cumsum() 函数返回沿给定轴的元素的累积总和。

Python numpy cumsum() 语法

cumsum() 方法语法是:

1cumsum(array, axis=None, dtype=None, out=None)
  • array可以是分列或类似数列的对象,如嵌入列表
  • 参数定义了计算累积总量的轴。如果没有提供轴,则数列被平衡,并为结果数列计算累积总和
  • dtype参数定义了输出数据类型,如浮动和int.
  • out选项参数用于指定结果的数列

Python numpy cumsum() 例子

让我们看看计算数组元素累积总量的几个例子。

Numpy Array 元素无轴的累积总和

1import numpy as np
2
3array1 = np.array(
4    [[1, 2],
5     [3, 4],
6     [5, 6]])
7
8total = np.cumsum(array1)
9print(f'Cumulative Sum of all the elements is {total}')

此分類上一篇: 所有元素的累積總和是 [ 1 3 6 10 15 21 ] 在這裡,數列首先被平衡到 [ 1 2 3 4 5 6 ],然後計算累積總和,結果是 [ 1 3 6 10 15 21 ] 。

(二)轴的累积总数

 1import numpy as np
 2
 3array1 = np.array(
 4    [[1, 2],
 5     [3, 4],
 6     [5, 6]])
 7
 8total_0_axis = np.cumsum(array1, axis=0)
 9print(f'Cumulative Sum of elements at 0-axis is:\n{total_0_axis}')
10
11total_1_axis = np.cumsum(array1, axis=1)
12print(f'Cumulative Sum of elements at 1-axis is:\n{total_1_axis}')

输出:

1Cumulative Sum of elements at 0-axis is:
2[[ 1 2]
3 [ 4 6]
4 [ 9 12]]
5Cumulative Sum of elements at 1-axis is:
6[[ 1 3]
7 [ 3 7]
8 [ 5 11]]

3. 指定累积总数数组的数据类型

1import numpy as np
2
3array1 = np.array(
4    [[1, 2],
5     [3, 4],
6     [5, 6]])
7
8total_1_axis = np.cumsum(array1, axis=1, dtype=float)
9print(f'Cumulative Sum of elements at 1-axis is:\n{total_1_axis}')

输出:

1Cumulative Sum of elements at 1-axis is:
2[[ 1. 3.]
3 [ 3. 7.]
4 [ 5. 11.]]

此分類上一篇: API Doc

Published At
Categories with 技术
Tagged with
comments powered by Disqus