简体   繁体   中英

How to get the sum of a slice of an n-dimensional array in numpy?

I have an n-dimensional array in NumPy. I would like to calculate the sum of all the elements in a slice. For instance:

if I have the following 2x2x2 3D array having the values:

z = 1
1 2
3 4

z = 2
5 6
7 8

When I get a slice for z = 1 I would like to get 10 and for z = 2 I would like to get 26.

I can use the following for a 3D space but how can I do that for n dimensional space?

(array.sum(axis = 0)).sum(axis = 0)

I think you are over complicating this:

>>> a=(np.arange(8)+1).reshape(2,2,2)
>>> a
array([[[1, 2],
        [3, 4]],

       [[5, 6],
        [7, 8]]])
>>> np.sum(a[0])
10
>>> np.sum(a[1])
26
>>> a[:,0]
array([[1, 2],
       [5, 6]])
>>> np.sum(a[:,0])
14

沿第darr.take([i], axis=d).sum()i个切片的总和: arr.take([i], axis=d).sum()

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