将一系列numpy数组合并为一个数组(快速)

25

如果我们知道列表的长度和其中所有数组的大小(大小相同),那么将一个numpy数组列表合并为一个数组的最快方法是什么?

我尝试了两种方法:

如您所见,vstack更快,但由于(缺失)预分配的原因,第一次运行需要比第二次运行慢三倍。那么,如何为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"

2
使用timeit在Python中进行简单的性能测试。它可以产生更准确的结果。 - Björn Pollex
2
你想要合并后的数组有什么维度?因为“first1”是“(80, 320, 320)”,而“first2”是“(25280, 320)”。 - joris
@joris,感谢您指出这一点。我想要第二个选项,这是我的初始方法。我会在问题中进行更改。 - Framester
2
那么你需要使用“vstack”而不是eumiro答案中的“dstack”。 - joris
1个回答

22

你有80个大小为320x320的数组?那么你可能想使用dstack


first3 = numpy.dstack(firstmatrices)

这段代码返回一个大小为80x320x320的数组,就像numpy.array(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

如果你想使用vstack,它将返回一个25600x320的数组:

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

嗨eurmiro,抱歉我的问题不够清晰。我实际上需要的是(25280,320),而不是(80,320,320)。请查看我的问题更新。 - Framester

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接