- numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]#
-
Sum of array elements over a given axis.
- Parameters:
-
- aarray_like
-
Elements to sum.
- axisNone or int or tuple of ints, optional
-
Axis or axes along which a sum is performed. The default,
axis=None, will sum all of the elements of the input array. If
axis is negative it counts from the last to the first axis.New in version 1.7.0.
If axis is a tuple of ints, a sum is performed on all of the axes
specified in the tuple instead of a single axis or all the axes as
before. - dtypedtype, optional
-
The type of the returned array and of the accumulator in which the
elements are summed. The dtype of a is used by default unless a
has an integer dtype of less precision than the default platform
integer. In that case, if a is signed then the platform integer
is used while if a is unsigned then an unsigned integer of the
same precision as the platform integer is used. - outndarray, optional
-
Alternative output array in which to place the result. It must have
the same shape as the expected output, but the type of the output
values will be cast if necessary. - keepdimsbool, optional
-
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.If the default value is passed, then keepdims will not be
passed through to thesum
method of sub-classes of
ndarray
, however any non-default value will be. If the
sub-class’ method does not implement keepdims any
exceptions will be raised. - initialscalar, optional
-
Starting value for the sum. See
reduce
for details.New in version 1.15.0.
- wherearray_like of bool, optional
-
Elements to include in the sum. See
reduce
for details.New in version 1.17.0.
- Returns:
-
- sum_along_axisndarray
-
An array with the same shape as a, with the specified
axis removed. If a is a 0-d array, or if axis is None, a scalar
is returned. If an output array is specified, a reference to
out is returned.
See also
ndarray.sum
-
Equivalent method.
add.reduce
-
Equivalent functionality of
add
. cumsum
-
Cumulative sum of array elements.
trapz
-
Integration of array values using the composite trapezoidal rule.
mean
,average
Notes
Arithmetic is modular when using integer types, and no error is
raised on overflow.The sum of an empty array is the neutral element 0:
For floating point numbers the numerical precision of sum (and
np.add.reduce
) is in general limited by directly adding each number
individually to the result causing rounding errors in every step.
However, often numpy will use a numerically better approach (partial
pairwise summation) leading to improved precision in many use-cases.
This improved precision is always provided when noaxis
is given.
Whenaxis
is given, it will depend on which axis is summed.
Technically, to provide the best speed possible, the improved precision
is only used when the summation is along the fast axis in memory.
Note that the exact precision may vary depending on other parameters.
In contrast to NumPy, Python’smath.fsum
function uses a slower but
more precise approach to summation.
Especially when summing a large number of lower precision floating point
numbers, such asfloat32
, numerical errors can become significant.
In such cases it can be advisable to use dtype=”float64” to use a higher
precision for the output.Examples
>>> np.sum([0.5, 1.5]) 2.0 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32) 1 >>> np.sum([[0, 1], [0, 5]]) 6 >>> np.sum([[0, 1], [0, 5]], axis=0) array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1) array([1, 5]) >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1) array([1., 5.])
If the accumulator is too small, overflow occurs:
>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8) -128
You can also start the sum with a value other than zero:
>>> np.sum([10], initial=5) 15
In this article, let’s discuss how to find the sum and product of NumPy arrays.
Sum of the NumPy array
Sum of NumPy array elements can be achieved in the following ways
Method #1: Using numpy.sum()
Syntax: numpy.sum(array_name, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Example:
Python3
import
numpy as np
def
main():
print
(
'Initialised array'
)
gfg
=
np.array([[
1
,
2
,
3
], [
4
,
5
,
6
]])
print
(gfg)
print
(np.
sum
(gfg, axis
=
1
))
print
(np.
sum
(gfg, axis
=
0
))
print
(np.
sum
(gfg))
b
=
np.array([
0
])
print
(np.
sum
(gfg, axis
=
1
, out
=
b))
print
(b)
print
(
'with axis parameter'
)
print
(np.
sum
(gfg, axis
=
0
, keepdims
=
True
))
print
(np.
sum
(gfg, axis
=
1
, keepdims
=
True
))
print
(
'without axis parameter'
)
print
(np.
sum
(gfg, keepdims
=
True
))
print
(
'using initial parameter in sum function'
)
print
(np.
sum
(gfg, initial
=
100
))
print
(
'using where parameter '
)
print
(np.
sum
(gfg, axis
=
0
, where
=
[
True
,
False
,
False
]))
if
__name__
=
=
"__main__"
:
main()
Output:
Initialised array [[1 2 3] [4 5 6]] [ 6 15] [5 7 9] 21 [21] [21] with axis parameter [[5 7 9]] [[ 6] [15]] without axis parameter [[21]] using initial parameter in sum function 121 using where parameter [5 0 0]
Note: using numpy.sum on array elements consisting Not a Number (NaNs) elements gives an error, To avoid this we use numpy.nansum() the parameters are similar to the former except the latter doesn’t support where and initial.
Method #2: Using numpy.cumsum()
Returns the cumulative sum of the elements in the given array.
Syntax: numpy.cumsum(array_name, axis=None, dtype=None, out=None)
Example:
Python3
import
numpy as np
def
main():
print
(
'Initialised array'
)
gfg
=
np.array([[
1
,
2
,
3
], [
4
,
5
,
6
]])
print
(
'original array'
)
print
(gfg)
print
(np.cumsum(gfg))
print
(np.cumsum(gfg, axis
=
1
))
b
=
np.array([[
None
,
None
,
None
], [
None
,
None
,
None
]])
np.cumsum(gfg, axis
=
1
, out
=
b)
print
(b)
if
__name__
=
=
"__main__"
:
main()
Output:
Initialised array original array [[1 2 3] [4 5 6]] [ 1 3 6 10 15 21] [[ 1 3 6] [ 4 9 15]] [[1 3 6] [4 9 15]]
Product of the NumPy array
Product of NumPy arrays can be achieved in the following ways
Method #1: Using numpy.prod()
Syntax: numpy.prod(array_name, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Example:
Python3
import
numpy as np
def
main():
print
(
'Initialised array'
)
gfg
=
np.array([[
1
,
2
,
3
], [
4
,
5
,
6
]])
print
(gfg)
print
(np.prod(gfg, axis
=
1
))
print
(np.prod(gfg, axis
=
0
))
print
(np.prod(gfg))
b
=
np.array([
0
])
print
(np.prod(gfg, axis
=
1
, out
=
b))
print
(b)
print
(
'with axis parameter'
)
print
(np.prod(gfg, axis
=
0
, keepdims
=
True
))
print
(np.prod(gfg, axis
=
1
, keepdims
=
True
))
print
(
'without axis parameter'
)
print
(np.prod(gfg, keepdims
=
True
))
print
(
'using initial parameter in sum function'
)
print
(np.prod(gfg, initial
=
10
))
print
(
'using where parameter '
)
print
(np.prod(gfg, axis
=
0
, where
=
[
True
,
False
,
False
]))
if
__name__
=
=
"__main__"
:
main()
Output:
Initialised array [[1 2 3] [4 5 6]] [ 6 120] [ 4 10 18] 720 [720] [720] with axis parameter [[ 4 10 18]] [[ 6] [120]] without axis parameter [[720]] using initial parameter in sum function 7200 using where parameter [4 1 1]
Method #2: Using numpy.cumprod()
Returns a cumulative product of the array.
Syntax: numpy.cumsum(array_name, axis=None, dtype=None, out=None)axis = [integer,Optional]
Python3
import
numpy as np
def
main():
print
(
'Initialised array'
)
gfg
=
np.array([[
1
,
2
,
3
], [
4
,
5
,
6
]])
print
(
'original array'
)
print
(gfg)
print
(np.cumprod(gfg))
print
(np.cumprod(gfg, axis
=
1
))
b
=
np.array([[
None
,
None
,
None
], [
None
,
None
,
None
]])
np.cumprod(gfg, axis
=
1
, out
=
b)
print
(b)
if
__name__
=
=
"__main__"
:
main()
Output:
Initialised array original array [[1 2 3] [4 5 6]] [ 1 2 6 24 120 720] [[ 1 2 6] [ 4 20 120]] [[1 2 6] [4 20 120]]
Last Updated :
14 Dec, 2021
Like Article
Save Article
In this tutorial, we will look at how to get the sum of values of a numpy array. We will also look at specific use-cases like summing along an axis for higher dimensional arrays.
How to sum a numpy array?
You can use the numpy sum()
function to sum elements of an array. The following is the syntax for a range of different use-cases:
# arr is a numpy array # sum of all values arr.sum() # sum of each row (for 2D array) arr.sum(axis=1) # sum of each column (for 2D array) arr.sum(axis=0) # sum along a specific axis, n arr.sum(axis=n)
You can also specify the axis to sum the numpy array along with the axis
parameter (see the examples below)
Let’s now look at some of the use-cases of using the numpy sum()
function.
Sum of all elements in the array
Use the numpy sum()
function without any parameters to get the sum total of all values inside the array.
Let’s create a numpy array and illustrate its usage.
import numpy as np # create an array arr = np.array([2, 0, 1, 3]) # sum of array values total = arr.sum() print(total)
Output:
6
We get 6 as the output which is the sum of all values in the above array arr: 2+0+1+3
You can use the above syntax to sum values in higher dimensional numpy arrays as well. For example, let’s get the total of all elements in a 2D numpy array –
# create a 2D numpy array arr = np.array([[1, 0, 0], [2, 1, 1]]) # sum of array values total = arr.sum() # display the array and the sum print(arr) print("Sum:", total)
Output:
[[1 0 0] [2 1 1]] Sum: 5
Here, we created a 2D array and then calculated its sum. You can see that we get the sum of all the elements in the above 2D array with the same syntax. This can be extended to higher-dimensional numpy arrays as well.
Sum of every row in a 2D array
To get the sum of each row in a 2D numpy array, pass axis=1
to the sum()
function. This argument tells the function of the axis along which the elements are to be summed. Let’s use it to get the sum of each row in the array arr.
# create a 2D numpy array arr = np.array([[1, 0, 0], [2, 1, 1]]) # sum of each row row_totals = arr.sum(axis=1) # display the array and the sum print(arr) print("Sum of each row:", row_totals)
Output:
[[1 0 0] [2 1 1]] Sum of each row: [1 4]
We get the sum of each row with axis=1. The first row sums to 1 and the second-row sums to 4. The result is returned as a numpy array.
Sum of every column in a 2D array
To get the sum of each column in a 2D numpy array, pass axis=0
to the sum()
function. This argument tells the function of the axis along which the elements are to be summed. Let’s use it to get the sum of each column in the array arr.
# create a 2D numpy array arr = np.array([[1, 0, 0], [2, 1, 1]]) # sum of each column col_totals = arr.sum(axis=0) # display the array and the sum print(arr) print("Sum of each column:", col_totals)
Output:
[[1 0 0] [2 1 1]] Sum of each column: [3 1 1]
The resulting array [3, 1, 1]
contains the sum of values in each column. That is, in the above example – 1+2, 0+1, and 0+1.
The numpy sum() function also has additional parameters, for example, to specify the data type of the output, etc. For more, refer to its documentation.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Tutorials on numpy arrays –
- How to sort a Numpy Array?
- Create Pandas DataFrame from a Numpy Array
- Different ways to Create NumPy Arrays
- Convert Numpy array to a List – With Examples
- Append Values to a Numpy Array
- Find Index of Element in Numpy Array
- Read CSV file as NumPy Array
- Filter a Numpy Array – With Examples
- Python – Randomly select value from a list
- Numpy – Sum of Values in Array
- Numpy – Elementwise sum of two arrays
- Numpy – Elementwise multiplication of two arrays
- Using the numpy linspace() method
- Using numpy vstack() to vertically stack arrays
- Numpy logspace() – Usage and Examples
- Using the numpy arange() method
- Using numpy hstack() to horizontally stack arrays
- Trim zeros from a numpy array in Python
- Get unique values and counts in a numpy array
- Horizontally split numpy array with hsplit()
-
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.
View all posts
Функция numpy.sum() в Python используется для получения суммы элементов массива по заданной оси.
Содержание
- Синтаксис функции
- Примеры
- 1. Сумма всех элементов в массиве
- 2. Сумма элементов массива вдоль оси
- 3. Указание типа выходных данных суммы
- 4. Начальное значение суммы
Синтаксис функции
Синтаксис метода:
sum(array, axis, dtype, out, keepdims, initial)
- Array (элементы массива) используются для вычисления суммы.
- Если axis не указана, возвращается сумма всех элементов. Если axis представляет собой кортеж целых чисел, возвращается сумма всех элементов в данных осях.
- Мы можем указать dtype, чтобы указать тип возвращаемых выходных данных.
- Переменная out используется для указания массива для размещения результата. Это необязательный параметр.
- Keepdims – это логический параметр. Если установлено значение True, уменьшенные оси останутся в результате с размером один.
- Initial (первоначальный параметр) указывает начальное значение суммы.
Примеры
Давайте посмотрим на некоторые примеры функции numpy sum().
1. Сумма всех элементов в массиве
Если мы передаем в функцию sum() только массив, он выравнивается и возвращается сумма всех элементов.
import numpy as np array1 = np.array( [[1, 2], [3, 4], [5, 6]]) total = np.sum(array1) print(f'Sum of all the elements is {total}')
Вывод: сумма всех элементов равна 21.
2. Сумма элементов массива вдоль оси
Если мы указываем значение оси, возвращается сумма элементов вдоль этой оси. Если форма массива (X, Y), тогда сумма по оси 0 будет иметь форму (1, Y). Сумма по 1-ой оси будет иметь форму (1, X).
import numpy as np array1 = np.array( [[1, 2], [3, 4], [5, 6]]) total_0_axis = np.sum(array1, axis=0) print(f'Sum of elements at 0-axis is {total_0_axis}') total_1_axis = np.sum(array1, axis=1) print(f'Sum of elements at 1-axis is {total_1_axis}')
Вывод:
Sum of elements at 0-axis is [ 9 12] Sum of elements at 1-axis is [ 3 7 11]
3. Указание типа выходных данных суммы
import numpy as np array1 = np.array( [[1, 2], [3, 4]]) total_1_axis = np.sum(array1, axis=1, dtype=float) print(f'Sum of elements at 1-axis is {total_1_axis}')
Выход: сумма элементов на 1 оси равна [3. 7.].
4. Начальное значение суммы
import numpy as np array1 = np.array( [[1, 2], [3, 4]]) total_1_axis = np.sum(array1, axis=1, initial=10) print(f'Sum of elements at 1-axis is {total_1_axis}')
Выход: сумма элементов на 1 оси равна [13 17].
( 2 оценки, среднее 5 из 5 )
Помогаю в изучении Питона на примерах. Автор практических задач с детальным разбором их решений.
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
numpy.sum(arr, axis, dtype, out) : This function returns the sum of array elements over the specified axis.
Parameters :
arr : input array.
axis : axis along which we want to calculate the sum value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.
out : Different array in which we want to place the result. The array must have same dimensions as expected output. Default is None.
initial : [scalar, optional] Starting value of the sum.
Return : Sum of the array elements (a scalar value if axis is none) or array with sum values along the specified axis.
Code #1:
Python3
import
numpy as np
arr
=
[
20
,
2
, .
2
,
10
,
4
]
print
("nSum of arr : ", np.
sum
(arr))
print
("
Sum
of arr(uint8) : ", np.
sum
(arr, dtype
=
np.uint8))
print
("
Sum
of arr(float32) : ", np.
sum
(arr, dtype
=
np.float32))
print
("nIs np.
sum
(arr).dtype
=
=
np.uint : ",
np.
sum
(arr).dtype
=
=
np.uint)
print
("Is np.
sum
(arr).dtype
=
=
np.
float
: ",
np.
sum
(arr).dtype
=
=
np.
float
)
Output:
Sum of arr : 36.2 Sum of arr(uint8) : 36 Sum of arr(float32) : 36.2 Is np.sum(arr).dtype == np.uint : False Is np.sum(arr).dtype == np.float : True
Code #2:
Python3
import
numpy as np
arr
=
[[
14
,
17
,
12
,
33
,
44
],
[
15
,
6
,
27
,
8
,
19
],
[
23
,
2
,
54
,
1
,
4
,]]
print
("nSum of arr : ", np.
sum
(arr))
print
("
Sum
of arr(uint8) : ", np.
sum
(arr, dtype
=
np.uint8))
print
("
Sum
of arr(float32) : ", np.
sum
(arr, dtype
=
np.float32))
print
("nIs np.
sum
(arr).dtype
=
=
np.uint : ",
np.
sum
(arr).dtype
=
=
np.uint)
print
("Is np.
sum
(arr).dtype
=
=
np.
float
: ",
np.
sum
(arr).dtype
=
=
np.
float
)
Output:
Sum of arr : 279 Sum of arr(uint8) : 23 Sum of arr(float32) : 279.0 Is np.sum(arr).dtype == np.uint : False Is np.sum(arr).dtype == np.float : False
Code #3:
Python3
import
numpy as np
arr
=
[[
14
,
17
,
12
,
33
,
44
],
[
15
,
6
,
27
,
8
,
19
],
[
23
,
2
,
54
,
1
,
4
,]]
print
("nSum of arr : ", np.
sum
(arr))
print
("
Sum
of arr(axis
=
0
) : ", np.
sum
(arr, axis
=
0
))
print
("
Sum
of arr(axis
=
1
) : ", np.
sum
(arr, axis
=
1
))
print
("nSum of arr (keepdimension
is
True
): n",
np.
sum
(arr, axis
=
1
, keepdims
=
True
))
Output:
Sum of arr : 279 Sum of arr(axis = 0) : [52 25 93 42 67] Sum of arr(axis = 1) : [120 75 84] Sum of arr (keepdimension is True): [[120] [ 75] [ 84]]
Last Updated :
07 Nov, 2022
Like Article
Save Article