Skip to content Skip to sidebar Skip to footer

Iterating And Selecting A Specific Array From A Multidimensional Array In Python

Imagine I have something like this: 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

Solution 1:

You can use map to get this done:

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

Then the command:

map(sum, arra)

gives you the desired output:

[array([ 4,  6,  8, 10]), array([20, 22, 24, 26])]

Alternatively, you can also use a list comprehension:

res = [sum(ai) for ai in arra]

Then res looks like this:

[array([ 4,  6,  8, 10]), array([20, 22, 24, 26])]

EDIT:

If you want to add identical rows - as you mentioned in the comments below this answer - you can do (using zip):

map(sum, zip(*arra))

which gives you the desired output:

[array([ 8, 10, 12, 14]), array([16, 18, 20, 22])]

For the sake of completeness also the list comprehension:

[sum(ai) for ai inzip(*arra)]

which gives you the same output.

Post a Comment for "Iterating And Selecting A Specific Array From A Multidimensional Array In Python"