Convert 1D object numpy array of lists to 2D numeric array and back
<p>Say I have this object array containing lists of the same length:</p>

<pre><code>&gt;&gt;&gt; a = np.empty(2, dtype=object)
&gt;&gt;&gt; a[0] = [1, 2, 3, 4]
&gt;&gt;&gt; a[1] = [5, 6, 7, 8]
&gt;&gt;&gt; a
array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)
</code></pre>

<ol>
<li><p>How can I convert this to a numeric 2D array?</p>

<pre><code>&gt;&gt;&gt; a.shape
(2,)
&gt;&gt;&gt; b = WHAT_GOES_HERE(a)
&gt;&gt;&gt; b
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
&gt;&gt;&gt; b.shape
(2, 4)
</code></pre></li>
<li><p>How can I do the reverse?</p></li>
<li><p>Does it get easier if my <code>a</code> array is an <code>np.array</code> of <code>np.array</code>s, rather than an <code>np.array</code> of <code>list</code>s?</p>

<pre><code>&gt;&gt;&gt; na = np.empty(2, dtype=object)
&gt;&gt;&gt; na[0] = np.array([1, 2, 3, 4])
&gt;&gt;&gt; na[1] = np.array([5, 6, 7, 8])
&gt;&gt;&gt; na
array([array([1, 2, 3, 4]), ([5, 6, 7, 8])], dtype=object)
</code></pre></li>
</ol>

<p>One approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow"><code>np.concatenate</code></a> -</p>

<pre><code>b = np.concatenate(a).reshape(len(a),*np.shape(a[0]))
</code></pre>

<p>The improvement suggest by <code>@Eric</code> to use <code>*np.shape(a[0])</code> should make it work for generic <code>ND</code> shapes.</p>

<p>Sample run -</p>

<pre><code>In [183]: a
Out[183]: array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)

In [184]: a.shape
Out[184]: (2,)

In [185]: b = np.concatenate(a).reshape(len(a),*np.shape(a[0]))

In [186]: b
Out[186]: 
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

In [187]: b.shape
Out[187]: (2, 4)
</code></pre>

<hr>

<p>To get back <code>a</code>, it seems we can use a two-step process, like so -</p>

<pre><code>a_back = np.empty(b.shape[0], dtype=object)
a_back[:] = b.tolist()
</code></pre>

<p>Sample run -</p>

<pre><code>In [190]: a_back = np.empty(b.shape[0], dtype=object)
     ...: a_back[:] = b.tolist()
     ...: 

In [191]: a_back
Out[191]: array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=object)

In [192]: a_back.shape
Out[192]: (2,)
</code></pre>

python numpy