Reputation: 21961
I have a numpy array with following shape:
(365L, 280L, 300L)
I want to sum up the array across the first dimension (365), so that I get 365 values as result.
I can do np.sum()
, but how to specify which axis?
--EDIT:
The answer should have shape: (365,)
Upvotes: 1
Views: 121
Reputation: 152587
np.sum
allows the use of a tuple of integer
as axis
argument to calculate the sum along multiple axis at once:
import numpy as np
arr = ... # somearray
np.sum(arr, axis=(1, 2)) # along axis 1 and 2 (remember the first axis has index 0)
np.sum(arr, axis=(2, 1)) # the order doesn't matter
Or directly use the sum
method of the array:
arr.sum(axis=(1, 2))
The latter only works if arr
is already a numpy array. np.sum
works even if your arr
is a python-list
.
The option to use a tuple as axis
argument wasn't implemented yet but you could always nest multiple np.sum
or .sum
calls:
np.sum(np.sum(arr, axis=1), axis=1) # Nested sums
arr.sum(axis=2).sum(axis=1) # identical but more "sequential" than "nested"
Upvotes: 3
Reputation: 27575
Try this:
import numpy
a = numpy.random.random((365L, 280L, 300L)) # just an example
s = numpy.sum(a, axis=(1,2))
print s.shape
> (365,)
Upvotes: 2