title: Is there an alternative, vectored way to write the to_array function?
body: <p>Suppose we have a ragged, nested sequence like the following:</p>
  <pre class="lang-py prettyprint-override"><code>import numpy as np
  x = np.ones((10, 20))
  y = np.zeros((10, 20))
  a = [[0, x], [y, 1]]
  </code></pre>
  <p>and want to create a <em>full</em> <code>numpy</code> array that broadcasts the ragged sub-sequences (to match the maximum dimension of any other sub-sequence, in this case <code>(10,20)</code>) where necessary. First, we might try to use <code>np.array(a)</code>, which yields the warning:</p>
  <blockquote>
  <p><code>VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray</code></p>
  </blockquote>
  <p>By changing to <code>np.array(a, dtype=object)</code>, we do get an array. However, this is an array of objects rather than floats, and retains the ragged subsequences, which have not been broadcasted as desired. To fix this, I created a new function <code>to_array</code> which takes a (possibly ragged, nested) sequence and a shape and returns a full numpy array of that shape:</p>
  <pre class="lang-py prettyprint-override"><code>    def to_array(a, shape):
          a = np.array(a, dtype=object)
          b = np.empty(shape)
          for index in np.ndindex(a.shape):
              b[index] = a[index]
          return b
      
      b = np.array(a, dtype=object)
      c = to_array(a, (2, 2, 10, 20))
      
      print(b.shape, b.dtype) # prints (2, 2) object
      print(c.shape, c.dtype) # prints (2, 2, 10, 20) float64
  </code></pre>
  <p>Note that <code>c</code>, not <code>b</code>, is the desired result. However, <code>to_array</code> relies on a for loop over <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndindex.html" rel="nofollow noreferrer">nindex</a>, and Python for loops are slow for big arrays.</p>
  <p>Is there an alternative, vectorized way to write the <code>to_array</code> function?</p>