【问题标题】:Referencing index for vectorization in NumPyNumPy 中向量化的参考索引
【发布时间】:2021-09-23 15:23:34
【问题描述】:

我有几个 for 循环,我想对其进行矢量化以提高性能。它们在 1 x N 矩阵上运行。

for y in range(1, len(array[0]) + 1):
        array[0, y - 1] =  np.floor(np.nanmean(otherArray[0, ((y-1)*3):((y-1)*3+3)]))
for i in range(len(array[0])):
        array[0, int((i-1)*L+1)] = otherArray[0, i]

这些操作依赖于由 for 循环给出的数组索引。在使用 numpy.vectorize 时有什么方法可以访问索引,以便我可以将它们重写为向量化函数?

【问题讨论】:

  • 第二次迭代 i 可能会替换为 I = np.arange(len(array[0])) 并使用它进行一些计算。但是对于第一个循环中的切片,没有办法用数组替换迭代的y。在 a:b 切片中,ab 必须是标量。
  • 仅供参考:Python range(n) 从 0 开始,在 n-1 结束。 numpy 数组索引也是如此。使用 +1 为自己省去麻烦。

标签: python numpy vector vectorization


【解决方案1】:

第一个循环:

import numpy as np
array = np.zeros((1, 10))
otherArray = np.arange(30).reshape(1, -1)


print(f'array = \n{array}')
print(f'otherArray = \n{otherArray}')

for y in range(1, len(array[0]) + 1):
        array[0, y - 1] =  np.floor(np.nanmean(otherArray[0, ((y-1)*3):((y-1)*3+3)]))

print(f'array = \n{array}')

array = np.floor(np.nanmean(otherArray.reshape(-1, 3), axis = 1)).reshape(1, -1)

print(f'array = \n{array}')

输出:

array = 
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
otherArray = 
[[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
  24 25 26 27 28 29]]
array = 
[[ 1.  4.  7. 10. 13. 16. 19. 22. 25. 28.]]
array = 
[[ 1.  4.  7. 10. 13. 16. 19. 22. 25. 28.]]

第二次循环:

array = np.zeros((1, 10))
otherArray = np.arange(10, dtype = float).reshape(1, -1)
L = 1

print(f'array = \n{array}')
print(f'otherArray = \n{otherArray}')


for i in range(len(otherArray[0])):
        array[0, int((i-1)*L+1)] = otherArray[0, i]

print(f'array = \n{array}')


array = otherArray

print(f'array = \n{array}')

输出:

array = 
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
otherArray = 
[[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]]
array = 
[[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]]
array = 
[[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]]

【讨论】:

    【解决方案2】:

    看起来您在第一个循环中尝试计算移动平均线。最好这样做:

    import numpy as np
    
    
    window_width = 3
    arr = np.arange(12)
    
    out = np.floor(np.nanmean(arr.reshape(-1,window_width) ,axis=-1))
    
    print(out)
    

    关于你的第二个循环,我不知道它做了什么。您正在尝试将值从 otherArray 复制到具有一些偏移量的数组?我建议你看看 numpy 的切片功能。

    【讨论】:

      猜你喜欢
      • 2011-08-12
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      相关资源
      最近更新 更多