Convert List of List of Tuples Into 2d Numpy Array
<p>I have a list of list of tuples:</p>

<pre><code>X = [[(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)], [(0.5, 0.5, 0.52), (1.0, 1.0, 1.0)], [(0.5, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)]]
</code></pre>

<p>and would like to convert it to a 2D numpy array. I tried the following but didn't work. I just want to make sure the new transformed 2D keeps the same shape and structure of X. Please help me , thanks a lot.</p>

<pre><code>import numpy as np
X = [[(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)], [(0.5, 0.5, 0.52), (1.0, 1.0, 1.0)], [(0.5, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)]]
np.asarray([sublist for sublist in X])
</code></pre>

<p>Expected result would be:</p>

<pre><code>[[ 0.5 ,  0.5 ,  0.5 ],
    [ 1.  ,  1.  ,  1.  ]],

   [[ 0.5 ,  0.5 ,  0.52],
    [ 1.  ,  1.  ,  1.  ]],

   [[ 0.5 ,  0.52,  0.52],
    [ 1.  ,  1.  ,  1.  ]],

   [[ 0.52,  0.52,  0.52],
    [ 1.  ,  1.  ,  1.  ]],

   [[ 0.52,  0.52,  0.52],
    [ 1.  ,  1.  ,  1.  ]]
</code></pre>

<p>If I do the normal thing to your list I get a 3d array:</p>

<pre><code>In [38]: np.array(X)
Out[38]: 
array([[[ 0.5 ,  0.5 ,  0.5 ],
        [ 1.  ,  1.  ,  1.  ]],

       [[ 0.5 ,  0.5 ,  0.52],
        [ 1.  ,  1.  ,  1.  ]],

       [[ 0.5 ,  0.52,  0.52],
        [ 1.  ,  1.  ,  1.  ]],

       [[ 0.52,  0.52,  0.52],
        [ 1.  ,  1.  ,  1.  ]],

       [[ 0.52,  0.52,  0.52],
        [ 1.  ,  1.  ,  1.  ]]])
In [39]: _.shape
Out[39]: (5, 2, 3)
</code></pre>

<p>The <code>print</code> (str) display looks a lot like your desired result - except for the extra set of [] to enclose the whole thing:</p>

<pre><code>In [40]: print(__)
[[[ 0.5   0.5   0.5 ]
  [ 1.    1.    1.  ]]

 [[ 0.5   0.5   0.52]
  [ 1.    1.    1.  ]]

 [[ 0.5   0.52  0.52]
  [ 1.    1.    1.  ]]

 [[ 0.52  0.52  0.52]
  [ 1.    1.    1.  ]]

 [[ 0.52  0.52  0.52]
  [ 1.    1.    1.  ]]]
</code></pre>

<p>I could split it into a list of 5 2d arrays, but the display is rather different:</p>

<pre><code>In [43]: np.split(np.array(X),5)
Out[43]: 
[array([[[ 0.5,  0.5,  0.5],
         [ 1. ,  1. ,  1. ]]]), array([[[ 0.5 ,  0.5 ,  0.52],
         [ 1.  ,  1.  ,  1.  ]]]), array([[[ 0.5 ,  0.52,  0.52],
        ...]
</code></pre>

<p>A list comprehension turning each sublist into an array does the same thing, <code>[np.array(x) for x in X]</code></p>

<p>I could also reshape the <code>(5,2,3)</code> array into 2d arrays, (10,3) or (5,6) for example, but they won't look like your target.  </p>

<p>Is the <code>tuple</code> layer important (as opposed to being a list)?  I could preserve it (appearance wise) with a structured array: <code>np.array(X, dtype=('f,f,f'))</code>.</p>

python numpy