python - 在一个numpy数组(一个元组列表)中,通过扩展()多次处理速度很慢。我想让那部分更快
问题描述
有一个 numpy 数组,可以通过在 for 循环中组合一个元组数组来形成,例如此代码中的“res”。(变量名称和内容是根据实际代码简化的。)
仔细看这个,对于arr_2的长度,执行了一个for循环,执行了数组extends()。原来arr_2变长了,处理速度变得异常沉重。
不是可以通过做好数组创建来进行高速处理吗?
# -*- coding: utf-8 -*-
import numpy as np
arr_1 = np.array([[0, 0, 1], [0, 0.5, -1], [-1, 0, -1], [0, -0.5, -1], [1, 0, -1]])
arr_2 = np.array([[0, 1, 2], [0, 1, 2]])
all_arr = []
for p in arr_2:
all_arr = [
(arr_1[0], p), (arr_1[1], p), (arr_1[2], p),
(arr_1[0], p), (arr_1[1], p), (arr_1[4], p),
(arr_1[0], p), (arr_1[2], p), (arr_1[3], p),
(arr_1[0], p), (arr_1[3], p), (arr_1[4], p),
(arr_1[1], p), (arr_1[2], p), (arr_1[4], p),
(arr_1[2], p), (arr_1[3], p), (arr_1[4], p)]
all_arr.extend(all_arr)
vtype = [('type_a', np.float32, 3), ('type_b', np.float32, 3)]
res = np.array(all_arr, dtype=vtype)
print(res)
解决方案
通常使用结构化数组,按字段而不是元组列表方法分配更快:
In [388]: idx = [0,1,2,0,1,4,0,2,3,0,3,4,1,2,4,2,3,4]
In [400]: res1 = np.zeros(36, dtype=vtype)
In [401]: res1['type_a'][:18] = arr_1[idx]
In [402]: res1['type_a'][18:] = arr_1[idx]
In [403]: res1['type_b'][:18] = arr_2[0]
In [404]: res1['type_b'][18:] = arr_2[1]
In [405]: np.allclose(res['type_a'], res1['type_a'])
Out[405]: True
In [406]: np.allclose(res['type_b'], res1['type_b'])
Out[406]: True
推荐阅读
- javascript - 如何在 React Native 中将 UInt16 或字节转换为心跳率
- c++ - 无法应用数组 unique_ptr 的 to_address
- amazon-web-services - Cloudfront 到 s3 重定向到子域给出访问被拒绝错误
- python - Python:提高 keras 顺序模型的准确性
- php - 我如何将数据库连接到不属于我的远程服务器(运行 phpmyadmin)
- python - 根据值从熊猫数据框中的特定位置获取最后 N 行
- android - 在模拟器上启动应用程序时出错 - Android
- sockets - 你能判断一个 UDP 数据包是否比另一个数据包“年轻”吗?
- npm - NPM 警告需要必须由自我/更新节点安装的对等依赖项
- vb.net - VB.NET TableAdapter 未定义