Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy二维数组在某些索引上求和_Python_Numpy - Fatal编程技术网

Python numpy二维数组在某些索引上求和

Python numpy二维数组在某些索引上求和,python,numpy,Python,Numpy,有这样一个二维阵列: 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]] ] indices = [[0, 0], [0, 1]] # which means img[0][0] and img[0][1] # means here is represents 我只想得到某些指数的和,如下所示: img = [

有这样一个二维阵列:

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]]
]
indices = [[0, 0], [0, 1]] # which means img[0][0] and img[0][1]
# means here is represents
我只想得到某些指数的和,如下所示:

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]]
]
indices = [[0, 0], [0, 1]] # which means img[0][0] and img[0][1]
# means here is represents
在中的stackoverflow中有一个类似的关于1-d数组的问题,但当我尝试使用
打印(img[index])
时,它出现了一个错误。因为我想弄清楚,
img
的元素是那些通过指数表示的元素,然后得到它的平均和

预期产出

[5, 7, 9]
使用NumPy:

import numpy as np

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

当您提供一个奇特的索引时,索引元组的每个元素代表一个不同的轴。索引数组的形状将广播到您获得的输出的形状

在您的例子中,
index.T
的行是每个轴上的索引。您可以将它们转换为索引元组并附加
切片(无)
,这是
的编程等价物:
。可以直接获取生成的二维阵列的平均值:

img[tuple(indices.T) + (slice(None),)].sum(0)
另一种方法是使用splat操作符:

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

如果结果为[5,7,9],则该值为列表列上的总和。然后很简单:

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

array([5, 7, 9])

需要澄清的是,当您将[0,0]和[0,1]相加时,结果将是[5,7,9],或总计5+7+9=21?结果将是
[5,7,9]
您能否提供一个使用实际数组而不是列表的示例,显示预期的输出,还有不可转置的索引?这不太正确。@MadPhysician为什么?我很抱歉地说,我不清楚
img[0][0]+img[0][1]
应该是
[5,7,9]
,所以在这个答案中,当我将
轴=1
更改为
轴=0
@luneice编辑时,我得到了正确的答案。顺便问一下,你想要总数还是平均数?他基本上想要总数。注释很混乱“#表示图像[0][0]和图像[0][1]”,
表示
这里是
表示