Ohad Dan
Ohad Dan

Reputation: 2059

Sum ndarray values

Is there an easier way to get the sum of all values (assuming they are all numbers) in an ndarray :

import numpy as np

m = np.array([[1,2],[3,4]])

result = 0
(dim0,dim1) = m.shape
for i in range(dim0):
    for j in range(dim1):
        result += m[i,j]

print result

The above code seems somewhat verbose for a straightforward mathematical operation.

Thanks!

Upvotes: 1

Views: 8596

Answers (2)

ali_m
ali_m

Reputation: 74152

Just use numpy.sum():

result = np.sum(matrix)

or equivalently, the .sum() method of the array:

result = matrix.sum()

By default this sums over all elements in the array - if you want to sum over a particular axis, you should pass the axis argument as well, e.g. matrix.sum(0) to sum over the first axis.

As a side note your "matrix" is actually a numpy.ndarray, not a numpy.matrix - they are different classes that behave slightly differently, so it's best to avoid confusing the two.

Upvotes: 5

unutbu
unutbu

Reputation: 879191

Yes, just use the sum method:

result = m.sum()

For example,

In [17]: m = np.array([[1,2],[3,4]])

In [18]: m.sum()
Out[18]: 10

By the way, NumPy has a matrix class which is different than "regular" numpy arrays. So calling a regular ndarray matrix causes some cognitive dissonance. To help others understand your code, you may want to change the name matrix to something else.

Upvotes: 1

Related Questions