2011-05-17 11 views
18

リストの長さと配列のサイズが同じであれば、numpy配列のリストを1つの配列にマージする最も速い方法すべてのために? Pythonic way to create a numpy array from a list of numpy arraysからnumpy配列のリストを1つの配列にマージする(高速)

  • merged_array = array(list_of_arrays)

  • vstack

Aあなたはvstackが高速である見ることができますが、何らかの理由で最初の実行が3を取ります

は、私は2つのアプローチを試してみました秒より長い時間。私はこれが(欠落) preallocationによって引き起こされると仮定します。だから、私は vstackの配列をどのように事前に割り当てるのですか?それとももっと速い方法を知っていますか?

ありがとうございます!

[UPDATE]

私は、私のためにmerged_array = array(list_of_arrays)文句を言わない作業を意味(25280, 320)ない(80, 320, 320)れたいです。それを指摘してくれてありがとう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'](http://docs.python.org/library/timeit.html)を使用して、Pythonで簡単なパフォーマンステストを行います。より正確な結果が得られます。 –

+2

結合された配列にはどのような次元が必要ですか? '' first1''は ''(80、320、320) ''と '' first2''は '(25280,320)' ' – joris

+0

@jorisですので、それを指摘してくれてありがとうございます。私は最初のアプローチだった2番目のものが欲しい。私は質問でそれを変更します。 – Framester

答えて

18

あなたが持っている80個の配列の320×320?だから、おそらくdstackを使用したい:

timeit numpy.vstack(firstmatrices) 
100 loops, best of 3: 18.2 ms per loop 
:あなたは vstackを使用したい場合は

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 

が、それは25600x320配列を返します:

first3 = numpy.dstack(firstmatrices) 

これはnumpy.array(firstmatrices)がするよう1つの80x320x320配列を返します。

+0

こんにちはユーミロ、申し訳ありません、私の質問は不明でした。私は実際に(25280,320)必要ではなく(80,320,320)必要です。私の質問の更新を見てください。 – Framester

+0

@Framester - ok、単純な 'vstack'で私のアップデートを見てください。 – eumiro