Python numpy sum() 函数用于获取数组元素的总和。
Python numpy sum() 函数语法
Python NumPy sum() 方法语法是:
1sum(array, axis, dtype, out, keepdims, initial)
- 使用 array 元素来计算总和
- 如果未提供 轴,则返回所有元素的总和。如果轴是一组 ints,则返回给定的轴中的所有元素的总和 *我们可以指定 dtype来指定返回的输出数据类型 *使用 out 变量来指定位于结果的阵列。 这是一个可选的参数
- keepdims是一个布尔式参数。
Python numpy sum() 示例
让我们来看看 numpy sum() 函数的几个例子。
1、数组中的所有元素的总和
如果我们只在 sum() 函数中传递数组,它就会平衡,并返回所有元素的总和。
1import numpy as np
2
3array1 = np.array(
4 [[1, 2],
5 [3, 4],
6 [5, 6]])
7
8total = np.sum(array1)
9print(f'Sum of all the elements is {total}')
输出:所有元素的总和为21。
轴承沿线的数组元素总和
如果我们指定轴值,则返回沿该轴的元素的总和. 如果数组形状是(X,Y),那么沿0轴的总数将是形状(1,Y)。
1import numpy as np
2
3array1 = np.array(
4 [[1, 2],
5 [3, 4],
6 [5, 6]])
7
8total_0_axis = np.sum(array1, axis=0)
9print(f'Sum of elements at 0-axis is {total_0_axis}')
10
11total_1_axis = np.sum(array1, axis=1)
12print(f'Sum of elements at 1-axis is {total_1_axis}')
输出:
1Sum of elements at 0-axis is [ 9 12]
2Sum of elements at 1-axis is [ 3 7 11]
3、输出数据类型
1import numpy as np
2
3array1 = np.array(
4 [[1, 2],
5 [3, 4]])
6
7total_1_axis = np.sum(array1, axis=1, dtype=float)
8print(f'Sum of elements at 1-axis is {total_1_axis}')
** 输出**: 1轴元素的总和为 [3. 7.]
四、总值的初始值
1import numpy as np
2
3array1 = np.array(
4 [[1, 2],
5 [3, 4]])
6
7total_1_axis = np.sum(array1, axis=1, initial=10)
8print(f'Sum of elements at 1-axis is {total_1_axis}')
** 输出**: 1轴元素的总和是 [13 17]
** 参考**: API Doc