Numpy累积和:Python中高效使用numpy.cumsum()函数
Python 的 numpy.cumsum() 函数用于计算数组沿给定轴的累积和。
Python 中 NumPy 包 cumsum() 函数的语法
cumsum() 方法的语法如下:
cumsum(array, axis=None, dtype=None, out=None)
- array可以是- ndarray或类似数组的对象,例如嵌套列表。
- axis参数定义了计算累积和的轴。如果未提供- axis参数,则数组将被展平,并对展平后的结果数组计算累积和。
- dtype参数定义了输出数据类型,例如浮点型(- float)和整型(- int)。
- out可选参数用于指定存储结果的数组。
Python NumPy 库 cumsum() 函数的示例
让我们通过一些示例来了解如何计算 NumPy 数组元素的累积和。
1. 在不指定轴的情况下计算 NumPy 数组元素的累积和
import numpy as np
array1 = np.array(
    [[1, 2],
     [3, 4],
     [5, 6]])
total = np.cumsum(array1)
print(f'所有元素的累积和为 {total}')
输出:
所有元素的累积和为 [ 1  3  6 10 15 21]
在此示例中,数组 array1 首先被展平为 [1 2 3 4 5 6]。然后计算其累积和,得到 [1 3 6 10 15 21]。
2. 沿指定轴计算累积和
import numpy as np
array1 = np.array(
    [[1, 2],
     [3, 4],
     [5, 6]])
total_0_axis = np.cumsum(array1, axis=0)
print(f'沿 0 轴的累积和为:\n{total_0_axis}')
total_1_axis = np.cumsum(array1, axis=1)
print(f'沿 1 轴的累积和为:\n{total_1_axis}')
输出:
沿 0 轴的累积和为:
[[ 1  2]
 [ 4  6]
 [ 9 12]]
沿 1 轴的累积和为:
[[ 1  3]
 [ 3  7]
 [ 5 11]]
3. 为累积和数组指定数据类型
import numpy as np
array1 = np.array(
    [[1, 2],
     [3, 4],
     [5, 6]])
total_1_axis = np.cumsum(array1, axis=1, dtype=float)
print(f'沿 1 轴的累积和为:\n{total_1_axis}')
输出:
沿 1 轴的累积和为:
[[ 1.  3.]
 [ 3.  7.]
 [ 5. 11.]]
 
    