📅  最后修改于: 2023-12-03 15:34:02.857000             🧑  作者: Mango
The numpy.sum()
function computes the sum of array elements over a given axis.
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>)
a
– input arrayaxis
– which axis to sum over (None/integer/tuple of integers)dtype
– data type of returned arrayout
– output arraykeepdims
– whether to keep the dimensions after summingThe numpy.sum()
function returns the sum of all elements in the array if axis is not specified. If axis
is given, it returns an array with the sum of elements over the specified axis.
import numpy as np
# sum of all elements
a = np.array([[1, 2], [3, 4]])
print(np.sum(a)) # output: 10
# sum of each column
print(np.sum(a, axis=0)) # output: [4 6]
# sum of each row
print(np.sum(a, axis=1)) # output: [3 7]
In the above example, the numpy.sum()
function is used to compute the sum of all elements in the array a
. It is also used to compute the sum of elements over the columns (axis=0
) and the rows (axis=1
) of a
.
The numpy.sum()
function is a useful tool for computing the sum of array elements over a specified axis. It is frequently used in scientific computing and data analysis.