Python 中的 numpy.sum()函數

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

Python numpy sum() 函数语法

Python NumPy sum() 方法语法为:

sum(array, axis, dtype, out, keepdims, initial)
  • 使用 array 元素来计算总和。
  • 如果未提供 axis 参数,则返回所有元素的总和。如果轴是一组整数的元组,则返回给定轴上所有元素的总和。
  • 我们可以指定 dtype 来指定返回的输出数据类型。
  • out 变量用于指定放置结果的数组。这是一个可选参数。
  • keepdims 是一个布尔参数。如果设置为 True,则缩减的轴将作为大小为一的维度保留在结果中。
  • initial 参数指定总和的起始值。

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}')

輸出: 1軸元素的和為[13 17] 參考: API文件

Source:
https://www.digitalocean.com/community/tutorials/numpy-sum-in-python