Skip to content Skip to sidebar Skip to footer

Python Numpy 2d Array Sum Over Certain Indices

There is a 2-d array like this: img = [ [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[2, 2, 2], [3, 2, 3], [6, 7, 6]], [[9, 8, 1], [9, 8, 3], [9, 8, 5]] ] And i just want to get the

Solution 1:

Use NumPy:

import numpy as np

img = np.array(img)
img[tuple(indices)].sum(axis = 0)
#array([5, 7, 9])

Solution 2:

If the result would be [5, 7, 9] which is sum over the column of the list. Then easy:

img = np.asarray(img)
indices = [[0, 0], [0, 1]]
img[(indices)].sum(axis = 0)

Result:

array([5, 7, 9])

Solution 3:

When you supply a fancy index, each element of the index tuple represents a different axis. The shape of the index arrays broadcasts to the shape of the output you get.

In your case, the rows of indices.T are the indices in each axis. You can convert them into an index tuple and append slice(None), which is the programmatic equivalent of :. You can take the mean of the resulting 2D array directly:

img[tuple(indices.T) + (slice(None),)].sum(0)

Another way is to use the splat operator:

img[(*indices.T, slice(None))].sum(0)

Post a Comment for "Python Numpy 2d Array Sum Over Certain Indices"