将numpy数组的列表合并为一个数组(快速)内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (1)
• 关注 (0)
• 查看 (15)

• `merged_array = array(list_of_arrays)`从numpy数组列表创建numpy数组的Pythonic方法
• `vstack`

A你可以看到`vstack`速度更快，但出于某种原因，第一次运行所需时间是第二次运行的三倍。我想这是(失踪)引起的。将如何预先分配一个数组`vstack`是吗？或者你知道更快的方法吗？

```0.547468900681 s merged_array = array(first_list_of_arrays)
0.547191858292 s merged_array = array(second_list_of_arrays)
0.656183958054 s vstack first
0.236850976944 s vstack second```

```import numpy
import time
width = 320
height = 320
n_matrices=80

secondmatrices = list()
for i in range(n_matrices):
temp = numpy.random.rand(height, width).astype(numpy.float32)
secondmatrices.append(numpy.round(temp*9))

firstmatrices = list()
for i in range(n_matrices):
temp = numpy.random.rand(height, width).astype(numpy.float32)
firstmatrices.append(numpy.round(temp*9))

t1 = time.time()
first1=numpy.array(firstmatrices)
print time.time() - t1, "s merged_array = array(first_list_of_arrays)"

t1 = time.time()
second1=numpy.array(secondmatrices)
print time.time() - t1, "s merged_array = array(second_list_of_arrays)"

t1 = time.time()
first2 = firstmatrices.pop()
for i in range(len(firstmatrices)):
first2 = numpy.vstack((firstmatrices.pop(),first2))
print time.time() - t1, "s vstack first"

t1 = time.time()
second2 = secondmatrices.pop()
for i in range(len(secondmatrices)):
second2 = numpy.vstack((secondmatrices.pop(),second2))

print time.time() - t1, "s vstack second"```

1 个回答

`first3 = numpy.dstack(firstmatrices)`

```timeit numpy.dstack(firstmatrices)
10 loops, best of 3: 47.1 ms per loop

timeit numpy.array(firstmatrices)
1 loops, best of 3: 750 ms per loop```

```timeit numpy.vstack(firstmatrices)
100 loops, best of 3: 18.2 ms per loop```