📜  Python numpy.sum()(1)

📅  最后修改于: 2023-12-03 15:34:02.857000             🧑  作者: Mango

Python numpy.sum()

The numpy.sum() function computes the sum of array elements over a given axis.

Syntax
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>)
Parameters
  • a – input array
  • axis – which axis to sum over (None/integer/tuple of integers)
  • dtype – data type of returned array
  • out – output array
  • keepdims – whether to keep the dimensions after summing
Return Value

The 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.

Examples
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.

Conclusion

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.