title: Merging a list of numpy arrays into one array (fast)
body: <p>what would be the fastest way to merge a list of numpy arrays into one array if one knows the length of the list and the size of the arrays, which is the same for all?</p>
  
  <p>I tried two approaches:</p>
  
  <ul>
  <li><p><code>merged_array = array(list_of_arrays)</code> from <a href="https://stackoverflow.com/questions/2106287/pythonic-way-to-create-a-numpy-array-from-a-list-of-numpy-arrays">Pythonic way to create a numpy array from a list of numpy arrays</a> and</p></li>
  <li><p><code>vstack</code></p></li>
  </ul>
  
  <p>A you can see <code>vstack</code> is faster, but for some reason the first run takes three times longer than the second. I assume this caused by (missing) <a href="https://stackoverflow.com/questions/3491802/what-is-the-preferred-way-to-preallocate-numpy-arrays">preallocation</a>. So how would I preallocate an array for <code>vstack</code>? Or do you know a faster methode?</p>
  
  <p>Thanks!</p>
  
  <p><strong>[UPDATE]</strong></p>
  
  <p><strong>I want <code>(25280, 320)</code> not <code>(80, 320, 320)</code></strong> which means, <code>merged_array = array(list_of_arrays)</code> wont work for me. Thanks Joris for pointing that out!!!</p>
  
  <p><strong>Output:</strong></p>
  
  <pre><code>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
  </code></pre>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>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"
  </code></pre>