首页 > 解决方案 > NumPy 中向量化的参考索引

问题描述

我有几个 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 时有什么方法可以访问索引,以便我可以将它们重写为矢量化函数?

标签: pythonnumpyvectorvectorization

解决方案


第一个循环:

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

推荐阅读