行上的Numpy迭代

行上的Numpy迭代,numpy,numpy-ndarray,Numpy,Numpy Ndarray,例如,出于速度原因,我有一种误解,认为在Numpy中应该避免for循环 导入numpy a=numpy.array([[2,0,1,3],[0,2,3,1]] targets=numpy.array([[1,1,1,1,1,1]] 输出=numpy.zero((2,1)) 对于范围(2)中的i: 输出[i]=numpy.mean(目标[a[i]]) 这是获得每行选定位置平均值的好方法吗?感觉可能有办法先对数组进行切片,然后直接应用平均值。numpy实际上为您解释了这一点:targets[a]可

例如,出于速度原因,我有一种误解,认为在Numpy中应该避免for循环

导入numpy
a=numpy.array([[2,0,1,3],[0,2,3,1]]
targets=numpy.array([[1,1,1,1,1,1]]
输出=numpy.zero((2,1))
对于范围(2)中的i:
输出[i]=numpy.mean(目标[a[i]])

这是获得每行选定位置平均值的好方法吗?感觉可能有办法先对数组进行切片,然后直接应用平均值。

numpy
实际上为您解释了这一点:
targets[a]
可以“按行”工作,然后使用
np。平均值(targets[a],axis=1)
正如@hpaulj在注释中建议的那样,它完全满足您的需要:

import numpy

a = numpy.array([[2,0,1,3],[0,2,3,1]])
targets = numpy.arange(1,6) # To make the results differ
output = numpy.mean(targets[a], axis=1) # the i-th row of targets[a] is targets[a[i]]

numpy
实际上为您解释了这一点:
targets[a]
以“行”方式工作,随后使用
np.mean(targets[a],axis=1)
正如@hpaulj在注释中所建议的那样,完全符合您的要求:

import numpy

a = numpy.array([[2,0,1,3],[0,2,3,1]])
targets = numpy.arange(1,6) # To make the results differ
output = numpy.mean(targets[a], axis=1) # the i-th row of targets[a] is targets[a[i]]

我想你正在寻找这个:

targets[a].mean(1)

请注意,在您的示例中,
目标必须是一维而不是二维的。否则,您的循环将抛出绑定索引,因为它解释行索引而不是列索引的索引。

我认为您正在寻找以下内容:

targets[a].mean(1)

请注意,在您的示例中,
targets
需要是一维的,而不是二维的。否则,当循环解释行索引而不是列索引时,会抛出绑定索引。

目标[a]
看起来像什么?你能使用
np.mean的轴参数吗
目标[a]
是什么样子的?是否可以使用
np.mean
的轴参数?