Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

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 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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use NumPy:

import numpy as np

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...