sum() - Common NumPy Functions
The sum()
function is a commonly used function in NumPy that is used to find the sum of the values of an array along a specified axis. The function returns the sum of the elements of the array.
Syntax
The syntax for using the sum()
function in NumPy is as follows:
numpy.sum(arr, axis=None, dtype=None, out=None, keepdims=<no value>)
arr
: Input arrayaxis
: Axis along which the sum is to be computeddtype
: Type to use in computing the sumout
: Alternate output array in which to place the resultkeepdims
: If this is set toTrue
, the dimensions of the output array will be the same as the input array
Example
Consider the following example code that demonstrates the usage of the sum()
function:
import numpy as np
a = np.array([[1,2,3], [4,5,6]])
print("Array a:")
print(a)
print("Sum of all elements in the array:")
print(np.sum(a))
print("Sum along columns:")
print(np.sum(a, axis=0))
print("Sum along rows:")
print(np.sum(a, axis=1))
Output
The output of the above code will be:
Array a:
[[1 2 3]
[4 5 6]]
Sum of all elements in the array:
21
Sum along columns:
[5 7 9]
Sum along rows:
[ 6 15]
Explanation
In the above example, we create a 2-dimensional array a
with 2 rows and 3 columns. We then use the sum()
function to find the sum of all the elements of the array, along the vertical axis (default value). We also use the sum()
function to find the sum along the columns and rows.
Use
The sum()
function is useful in a variety of contexts, such as in mathematical computations, data analysis, and image processing. It allows you to find the sum of elements along a given axis, which is useful for computing aggregate values.
Important Points
- The
keepdims
parameter, when set toTrue
, retains the original dimensions of the array in the output. This parameter is useful when you want to preserve the original shape of the array while performing operations on it. - The
dtype
parameter of thesum()
function determines the data type of the output. If it is not specified, the function will try to infer the data type automatically. - When computing the sum of a multi-dimensional array, the
axis
parameter specifies the direction along which the sum will be computed.
Summary
The sum()
function in NumPy is used to compute the sum of elements of an array along a specified axis. It is a useful function in many contexts and has parameters such as axis
, dtype
, and keepdims
that control the behavior of the function. The function returns the sum of the elements of the array.