1

This is a question that comes from the post here 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.

1 Answer 1

1

Depending on the how exactly arra is defined, you can shift your values appropriately using np.roll:

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

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.