在Python中使用numpy.sum()
Python的numpy.sum()函数用于沿给定轴获取数组元素的和。
Python的numpy库中sum()函数的语法。
Python NumPy sum()方法的语法是:
sum(array, axis, dtype, out, keepdims, initial)
- The array elements are used to calculate the sum.
- If the axis is not provided, the sum of all the elements is returned. If the axis is a tuple of ints, the sum of all the elements in the given axes is returned.
- We can specify dtype to specify the returned output data type.
- The out variable is used to specify the array to place the result. It’s an optional parameter.
- The keepdims is a boolean parameter. If this is set to True, the axes which are reduced are left in the result as dimensions with size one.
- The initial parameter specifies the starting value for the sum.
Python numpy sum() 示例
让我们来看一些numpy.sum()函数的示例。
数组中所有元素的总和
如果我们只通过数组将其传递给 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}')
输出:一维轴上元素之和为[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文档