简体   繁体   中英

Adding numpy 3D array across one dimension

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

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM