python中的numpy.sum()

时间:2020-02-23 14:42:22  来源:igfitidea点击:

Python numpy sum()函数用于获取给定轴上的数组元素之和。

Python numpy sum()函数语法

Python NumPy sum()方法语法为:

sum(array, axis, dtype, out, keepdims, initial)
  • 数组元素用于计算总和。

  • 如果未提供轴,则返回所有元素的总和。
    如果轴是整数元组,则返回给定轴中所有元素的总和。

  • 我们可以指定dtype来指定返回的输出数据类型。

  • out变量用于指定要放置结果的数组。
    这是一个可选参数。

  • keepdims是一个布尔参数。
    如果将其设置为True,则缩小的轴将保留为尺寸1的尺寸。

  • 初始参数指定总和的起始值。

Python numpy sum()示例

我们来看一些numpy sum()函数的示例。

1.数组中所有元素的总和

如果我们仅在sum()函数中传递数组,则将其展平并返回所有元素的总和。

import numpy as np

array1 = np.array(
  [[1, 2],
   [3, 4],
   [5, 6]])

total = np.sum(array1)
print(f'Sum of all the elements is {total}')

输出:所有元素的总和为21

2.沿轴的数组元素之和

如果指定轴值,则返回沿该轴的元素之和。
如果数组形状为(X,Y),则沿0轴的和将为(1,Y)。
沿1轴的和将为(1,X)。

import numpy as np

array1 = np.array(
  [[1, 2],
   [3, 4],
   [5, 6]])

total_0_axis = np.sum(array1, axis=0)
print(f'Sum of elements at 0-axis is {total_0_axis}')

total_1_axis = np.sum(array1, axis=1)
print(f'Sum of elements at 1-axis is {total_1_axis}')

输出:

Sum of elements at 0-axis is [ 9 12]
Sum of elements at 1-axis is [ 3  7 11]

3.指定总和的输出数据类型

import numpy as np

array1 = np.array(
  [[1, 2],
   [3, 4]])

total_1_axis = np.sum(array1, axis=1, dtype=float)
print(f'Sum of elements at 1-axis is {total_1_axis}')

输出:1轴上的元素总数为[3.7.]

4.总和的初始值

import numpy as np

array1 = np.array(
  [[1, 2],
   [3, 4]])

total_1_axis = np.sum(array1, axis=1, initial=10)
print(f'Sum of elements at 1-axis is {total_1_axis}')