Skip to content Skip to sidebar Skip to footer

Choosing And Iterating Specific Sub-arrays In Multidimensional Arrays In Python

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 or

Solution 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]))

Post a Comment for "Choosing And Iterating Specific Sub-arrays In Multidimensional Arrays In Python"