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>Here's an approach that converts the source NumPy array to lists and then into the desired NumPy array:</p>

<pre><code>b = np.array([k for k in a])
b
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
c = np.array([k for k in b], dtype=object)
c
array([[1, 2, 3, 4],
       [5, 6, 7, 8]], dtype=object)
</code></pre>

python numpy