首页 > 解决方案 > 在一个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)

标签: pythonalgorithmnumpy

解决方案


通常使用结构化数组,按字段而不是元组列表方法分配更快:

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

推荐阅读