NumPy cumsum()

cumsum() 函数用于沿指定轴或跨所有轴计算数组元素的累积和。

示例

import numpy as np

# create a NumPy array
array1 = np.array([1, 2, 3, 4, 5])

# calculate the cumulative sum of the array elements cumulative_sum = np.cumsum(array1)
print(cumulative_sum) # Output : [ 1 3 6 10 15]

cumsum() 语法

cumsum() 的语法是:

numpy.cumsum(array, axis=None, dtype=None, out=None)

cumsum() 参数

cumsum() 函数接受以下参数:

  • array - 输入数组
  • axis (可选) - 计算累积和的轴
  • dtype (可选) - 返回的累积和的数据类型
  • out (可选) - 用于存储结果的输出数组

cumsum() 返回值

cumsum() 函数返回一个数组,其中包含沿指定轴或跨所有轴的元素的累积和。


示例 1:2D 数组的 cumsum()

axis 参数定义了如何计算 2D 数组元素的和。

  • 如果 axis = None,则数组被展平,并返回展平数组的累积和。
  • 如果 axis = 0,则按列计算累积和。
  • 如果 axis = 1,则按行计算累积和。

让我们看一个例子。

import numpy as np

# create a 2-D array
array1 = np.array([[1, 2, 3],
                                [4, 5, 6],
                                [7, 8, 9]])

# calculate cumulative sum of elements of the flattened array result1 = np.cumsum(array1)
print('Cumulative Sum of flattened array: ', result1)
# calculate the cumulative sum along the rows (axis=1) cumulative_sum_rows = np.cumsum(array1, axis=1)
# calculate the cumulative sum along the columns (axis=0) cumulative_sum_cols = np.cumsum(array1, axis=0)
print("\nCumulative sum along rows:") print(cumulative_sum_rows) print("\nCumulative sum along columns:") print(cumulative_sum_cols)

输出

Cumulative Sum of flattened array:  [ 1  3  6 10 15 21 28 36 45]

Cumulative sum along rows:
[[ 1  3  6]
 [ 4  9 15]
 [ 7 15 24]]

Cumulative sum along columns:
[[ 1  2  3]
 [ 5  7  9]
 [12 15 18]]

示例 2:cumsum() 中 dtype 参数的使用

import numpy as np

# create an array
array1 = np.array([1, 2, 3, 4, 5])

# calculate the cumulative sum of array1 with the specified data type as float cumulative_sum_float = np.cumsum(array1, dtype=float)
print(cumulative_sum_float)

输出

[ 1.  3.  6. 10. 15.]

这里,dtype 参数用于指定结果累积和的数据类型。

在本例中,我们使用 dtype=float 将数据类型设置为 float。这意味着结果累积和的元素类型将是 float


示例 3:cumsum() 中 out 参数的使用

import numpy as np

# create an array
array1 = np.array([1, 2, 3, 4, 5])

# create an empty array with the same shape as array1
out_array = np.zeros_like(array1)

# calculate the cumulative sum of array1 and store the result in out_array np.cumsum(array1, out=out_array)
print(out_array)

输出

[ 1  3  6 10 15]
[ 1.  3.  6. 10. 15.]

在此,指定 out=out_array 后,array1 的累积和结果将存储在 out_array 数组中。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战