NumPy Sum Function Usage Guide
The sum function in the numpy library is used to calculate the sum of elements in an array.
Usage:
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=)
Parameter description:
- Array
- Axis: Specifies the axis along which the calculations are performed. The default is None, which means all elements are summed. If axis=0 is specified, the sum is taken along the columns; if axis=1 is specified, the sum is taken along the rows.
- dtype: specifies the data type of the returned value, by default is None, which means it will retain the original data type of the array.
- Output: Specify the output array to store the computed results.
- “keepdims: maintain the dimensions of the output array. If set to True, the result will have the same dimensions as the input array, but if set to False, the result will be a simplified array.”
Return value:
Return an array or a scalar indicating the sum of the elements in the array.
Original: 我很高兴能帮助你。
Paraphrased: I’m glad I could help you.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(np.sum(a)) # 输出15
b = np.array([[1, 2, 3], [4, 5, 6]])
print(np.sum(b)) # 输出21
c = np.array([[1, 2, 3], [4, 5, 6]])
print(np.sum(c, axis=0)) # 输出[5 7 9]
d = np.array([[1, 2, 3], [4, 5, 6]])
print(np.sum(d, axis=1)) # 输出[ 6 15]
e = np.array([[1, 2, 3], [4, 5, 6]])
print(np.sum(e, axis=1, keepdims=True)) # 输出[[ 6] [15]]
In the above code, the sum of elements in arrays a, b, c, d, and e is calculated separately.