I often need to do summations over certain rows or columns of a larger NumPy array. For example, take this array:
>>> c = np.arange(18).reshape(3, 6)
>>> print(c)
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]]
Suppose I want to sum only where the row index is 0 or 2, AND the column index is either 0, 2, 4, or 5. In other words, I want the sum of the subarray
[[ 0 2 4 5]
[12 14 16 17]]
I generally do this with NumPy's incredibly useful ix_ method; e.g.
>>> np.sum(c[np.ix_([0,2],[0,2,4,5])])
70
So far, so good. Now, however, suppose I have a different array, e, that is like c, but has two leading dimensions. So its shape is (2,3,3,6) instead of just (3,6):
e = np.arange(108).reshape(2, 3, 3, 6)
(Please note that the actual arrays I am working with might contain any random integers; they do not contain consecutive integers like this example.)
What I'm looking to do is the calculation above for each row/column combination. The following works for this simple example, but for larger arrays with more dimensions this can be really, really slow:
new_sum = np.empty((2,3))
for i in range(2):
for j in range(3):
temp_array = e[i,j,:,:]
new_sum[i,j] = np.sum(temp_array[np.ix_([0,2],[0,2,4,5])])
The question: Can the above be accomplished in a faster way, presumably without resorting to using loops?
As a footnote, the result of the above is the following:
>>> print(new_sum)
[[ 70. 214. 358.]
[502. 646. 790.]]
Of course, the 70 in the upper-left is the same result we got before.