What is the method in NumPy to sum the last two axes of an array?

I was going through these threads:

And I found different ways to add up two arrays with each other. I have a question in my assignment where I am supposed to add the last axes of an array and I’m perplexed about how to do it, can anyone provide me with its solution?

1 Like

I can provide you with a solution to sum the last two axes of a NumPy array. Here’s the code for it:

The code transposes the input array to swap the last two axes using np.transpose(). Then, it reshapes the array to combine the last two axes into a single axis. Finally, the transposed and reshaped array is used as input to np.sum() with axis=-1 to sum over the last two axes.

I hope this helps!