如果知道列表长度和数组大小,将numpy数组列表合并为一个数组的最快方法是什么对全部?将numpy数组列表合并为一个数组(快速)
我尝试了两种方法:
merged_array = array(list_of_arrays)
从Pythonic way to create a numpy array from a list of numpy arrays和vstack
一个你可以看到vstack
速度较快,但由于某种原因,第一次运行需要三个次数比第二次长。我认为这是由(缺少)preallocation造成的。那么我如何为vstack
预分配一个数组?或者你知道更快的方法吗?
谢谢!
[更新]
我想(25280, 320)
不(80, 320, 320)
这意味着,merged_array = array(list_of_arrays)
我不会工作。感谢Joris指出了这一点!
输出:
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"
使用['timeit'](http://docs.python.org/library/timeit.html)在Python中进行简单的性能测试。它产生更准确的结果。 – 2011-05-17 12:45:57
您希望合并的数组具有哪些维度?因为''first1''是''(80,320,320)'',而'first2''是''(25280,320)' – joris 2011-05-17 13:02:09
@joris,谢谢指出。我想要第二个,这是我最初的方法。我会在这个问题上改变它。 – Framester 2011-05-17 13:06:57