Choosing and iterating specific sub-arrays in multidimensional arrays in Python
Question: This is a question that comes from the post here [Iterating and selecting a
specific array from a multidimensional array in
Python](http://stackoverflow.com/questions/35769536/iterating-and-selecting-a-
specific-array-from-a-multidimensional-array-in-python)

In that post, user @Cleb solved what it was my original problem: how to
perform a sum through columns in a 3d array:

    
    
     import numpy as np
     arra = np.arange(16).reshape(2, 2, 4)  
    

which gives

    
    
     array([[[0, 1, 2, 3],  
         [4, 5, 6, 7]],  
         [[8, 9, 10, 11],  
         [12, 13, 14, 15]]])  
    

and the problem was how to perform the sum of columns in each matrix, i. e., 0
+ 4, 1 + 5, ... , 8 + 12, ..., 11 + 15. It was solved by @Cleb.

Then I wondered how to do it in the case of a sum of 0 + 8, 1 + 9, ..., 4 +
12, ..., 7 + 15, (odd and even columns) which was also solved by @Cleb.

But then I wondered if there are a general idea (which can be modified in each
specific case). Imagine you can add the first and the last rows and the center
rows, in columns, separately, i. e., 0 + 12, 1 + 13, ..., 3 + 15, 4 + 8, 5 +
9, ..., 7 + 11.

Is there a general way? Thank you.


Answer: Depending on the how exactly `arra` is defined, you can shift your values
appropriately using
[`np.roll`](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.roll.html):

    
    
    arra_mod = np.roll(arra, arra.shape[2])
    

`arra_mod` then looks as follows:

    
    
    array([[[12, 13, 14, 15],
            [ 0,  1,  2,  3]],
    
           [[ 4,  5,  6,  7],
            [ 8,  9, 10, 11]]])
    

Now you can simply use the command from your [previous
question](http://stackoverflow.com/questions/35769536/iterating-and-selecting-
a-specific-array-from-a-multidimensional-array-in-python?lq=1) to get your
desired output:

    
    
    map(sum, arra_mod)
    

which gives you the desired output:

    
    
    [array([12, 14, 16, 18]), array([12, 14, 16, 18])]
    

You can also use a list comprehension

    
    
    [sum(ai) for ai in arra_mod]
    

which gives you the same output.

If you prefer one-liner, you can therefore simply do:

    
    
    map(sum, np.roll(arra, arra.shape[2]))
    

