0

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 sum of certain indices which are like this:

indices = [[0, 0], [0, 1]] # which means img[0][0] and img[0][1]
# means here is represents

There was a similar ask about 1-d array in stackoverflow in this link, but it got a error when I tried to use print(img[indices]). Because I want to make it clear that the element of img are those which indicates by indices, and then get the mean sum of it.

Expected output

[5, 7, 9]
3
  • Just to be cleared, when you sum [0,0] and [0,1], the result would be [5, 7, 9], or total 5 +7 + 9 = 21? Commented Jan 18, 2021 at 3:00
  • the result would be [5, 7, 9] Commented Jan 18, 2021 at 3:09
  • Can you provide an example that uses actual arrays, not lists, shows the expected output, and indices that aren't transposeable? Commented Jan 18, 2021 at 3:18

3 Answers 3

3

Use NumPy:

import numpy as np

img = np.array(img)
img[tuple(indices)].sum(axis = 0)
#array([5, 7, 9])
Sign up to request clarification or add additional context in comments.

10 Comments

@MadPhysicist why?
I am sorry to say that i did not clear that img[0][0] + img[0][1] should be [5, 7, 9], so in this answer i got the right answer when i changed the axis = 1 to axis = 0.
@luneice edited. by the way, you want the sum or the mean?
He want the sum basically. The comment is quite confuse "# which means image[0][0] and image[0][1]", means here is represents
Also, you want to transpose the indices most likely
|
1

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

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.