在numpy数组(元组列表)中,通过多次扩展()来降低处理速度。我想让那部分更快

In a numpy array (a list of tuples), the processing speed is slow by extending () many times. I want to make that part faster

提问人:alf02 提问时间:4/2/2020 更新时间:4/3/2020 访问量:266

问:

有一个 numpy 数组,可以通过将元组数组组合成一个 for 循环来形成,就像这段代码中的“res”一样。(变量名称和内容是从实际代码中简化而来的。

如果你仔细观察一下,就会发现一个 for 循环的长度为 arr_2,数组 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)
python 算法 numpy

评论


答:

0赞 Aly Hosny 4/2/2020 #1

我无法弄清楚你为什么使用这个索引,所以我只是复制了它arr_1

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

weird_idx = np.array([0,1,2,0,1,4,0,2,3,0,3,4,1,2,4,2,3,4])
weird_arr1 = arr_1[weird_idx]

all_arr = [(wiered_arr1[i],arr_2[j]) for j in range(len(arr_2)) for i in range(len(wiered_arr1)) ]

vtype = [('type_a', np.float32, 3), ('type_b', np.float32, 3)]
res = np.array(all_arr, dtype=vtype)

您也可以重复数组

arr1_rep = np.tile(weird_arr1.T,2).T 
arr2_rep = np.repeat(arr_2,weird_arr1.shape[0],0)
res = np.empty(arr1_rep.shape[0],dtype=vtype)
res['type_a']=arr1_rep
res['type_b']=arr2_rep

评论

0赞 alf02 4/3/2020
谢谢!下面使用 np.tile 和 np.repeat 的方法非常快。我没有想出。
0赞 hpaulj 4/3/2020 #2

通常,对于结构化数组,按字段分配比按元组列表方法分配更快:

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