1

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,)

2
  • 1
    numpy.sum takes an axis argument, so np.sum(X,axis=(1,2)) should do the trick. Commented Apr 28, 2016 at 21:36
  • The answer should have shape: (365,), using axis=0, I get shape (280, 300) Commented Apr 28, 2016 at 21:37

2 Answers 2

3

NumPy version >= 1.7

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.

NumPy version < 1.7:

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"
Sign up to request clarification or add additional context in comments.

Comments

2

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,)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.