Python numpy sum()函数用于沿指定轴计算数组元素的总和。
Python numpy sum()函数语法
Python NumPy sum()方法的语法是:
sum(array, axis, dtype, out, keepdims, initial)
- 使用数组元素计算总和。
- 如果未提供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