python - Sum ndarray values -
is there easier way sum of values (assuming numbers) in ndarray :
import numpy np m = np.array([[1,2],[3,4]]) result = 0 (dim0,dim1) = m.shape in range(dim0): j in range(dim1): result += m[i,j] print result
the above code seems verbose straightforward mathematical operation.
thanks!
just use numpy.sum()
:
result = np.sum(matrix)
or equivalently, .sum()
method of array:
result = matrix.sum()
by default sums on elements in array - if want sum on particular axis, should pass axis
argument well, e.g. matrix.sum(0)
sum on first axis.
as side note "matrix
" numpy.ndarray
, not numpy.matrix
- they different classes behave differently, it's best avoid confusing two.
Comments
Post a Comment