【问题标题】:Numpy iterating over rowsNumpy遍历行
【发布时间】:2020-06-29 03:51:50
【问题描述】:

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

import numpy

a = numpy.array([[2,0,1,3],[0,2,3,1]])
targets = numpy.array([[1,1,1,1,1,1,1]])
output = numpy.zeros((2,1))
for i in range(2):
    output[i] = numpy.mean(targets[a[i]])

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

【问题讨论】:

  • targets[a] 是什么样的?可以用np.mean的轴参数吗?

标签: numpy numpy-ndarray


【解决方案1】:

我想你正在寻找这个:

targets[a].mean(1)

请注意,在您的示例中,targets 必须是一维而不是二维。否则,您的循环会抛出超出范围的索引,因为它解释的是行索引而不是列索引。

【讨论】:

    【解决方案2】:

    numpy 实际上会为您解释这一点:targets[a] 按“行”工作,随后使用 @hpaulj 在 cmets 中建议的 np.mean(targets[a], axis=1) 完全符合您的要求:

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

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 1970-01-01
      • 2015-11-22
      • 2020-01-29
      • 2018-02-16
      • 2012-07-04
      • 1970-01-01
      • 2021-11-28
      • 2017-03-22
      相关资源
      最近更新 更多