python - 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 时有什么方法可以访问索引,以便我可以将它们重写为矢量化函数?
解决方案
第一个循环:
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.]]
推荐阅读
- c++ - 为什么 BRepMesh_IncrementalMesh 不起作用?
- amazon-web-services - EKS/Kubernetes 或 docker 中的容器是否有任何默认 RAM 限制?
- android - 在 Kotlin 多平台移动项目中访问设备和操作系统信息
- java - 并发问题使 vololitile 不起作用
- azure - `docker-compose up` 与 `docker compose up` 与环境变量
- tornado - PandasGUI 错误 — tornado.application — 回调函数 functools.partial 中的异常
- c# - c# 表未显示在 .db3 文件中
- python - 使用用户定义的 url 和文件名构建 python 网络爬虫函数
- moodle - 创建一个直接链接到 SCORM 包的 Moodle 课程
- android - 无法通过 RecyclerView 显示来自 Firebase 数据库的所有消息