首页 > 解决方案 > Numpy - 从数组列表创建数组的最有效方法

问题描述

我有一个程序,其当前的性能瓶颈涉及从相对较长的扁平数组的相对较短列表中创建一个新数组:

num_arrays = 5
array_length = 1000

arrays = [np.random.random((array_length, )) for _ in range(num_arrays)]

new_array = np.array(arrays)

换句话说,将nshape 数组堆叠(s,)new_arrayof shape (n, s)

我正在寻找最有效的方法来计算这个,因为这个操作重复了数百万次。

我测试了两种简单方法的性能:

%timeit np.array(arrays)
>>> 3.6 µs ± 67.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.stack(arrays)
>>> 9.61 µs ± 133 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

我目前正在使用np.array(arrays),但我想知道是否有更有效的方法来做到这一点。

一些可能有帮助的细节:

标签: pythonarraysperformancenumpy

解决方案


推荐阅读