Splitting numpy array field values that are matrices into column vectors
<p>I have the following numpy structured array:</p>

<pre><code>x = np.array([(22, 2, -1000000000.0, [1000,2000.0]), (22, 2, 400.0, [1000,2000.0])],
dtype=[('f1', '&lt;i4'), ('f2', '&lt;i4'), ('f3', '&lt;f4'), ('f4', '&lt;f4',2)])
</code></pre>

<p>As you can see, field 'f4' is a matrix:</p>

<pre><code>In [63]: x['f4']
Out[63]: 
array([[ 1000.,  2000.],
       [ 1000.,  2000.]], dtype=float32)
</code></pre>

<p>My end goal is to have a numpy structured array that only has vectors. I was wondering how to split 'f4' into two fields ('f41' and 'f42') where each field represents the column of the matrix.</p>

<pre><code>In [67]: x
Out[67]: 
array([(22, 2, -1000000000.0, 1000.0, 2000.0),
       (22, 2, 400.0, 1000.0, 2000.0)], 
      dtype=[('f1', '&lt;i4'), ('f2', '&lt;i4'), ('f3', '&lt;f4'), ('f41', '&lt;f4'), ('f42', '&lt;f4')])
</code></pre>

<p>Also i was wondering if it was possible to achieve this while using operations that modify the array in place or with minimal copying of the original data.</p>

<p>You can do this by creating a new view (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html" rel="nofollow">np.view</a>) of the array, which will not copy:</p>

<pre><code>import numpy as np

x = np.array([(22, 2, -1000000000.0, [1000,2000.0]),
              (22, 2, 400.0, [1000,2000.0])],
             dtype=[('f1', '&lt;i4'),
                    ('f2', '&lt;i4'),
                    ('f3', '&lt;f4'),
                    ('f4', '&lt;f4', 2)])
xNewView = x.view(dtype=[('f1', '&lt;i4'),
                         ('f2', '&lt;i4'),
                         ('f3', '&lt;f4'),
                         ('f41', '&lt;f4'),
                         ('f42', '&lt;f4')])
print(np.may_share_memory(x, xNewView)) # True
print(xNewView)
# array([(22, 2, -1000000000.0, 1000.0, 2000.0),
#        (22, 2, 400.0, 1000.0, 2000.0)], 
#       dtype=[('f1', '&lt;i4'),  ('f2', '&lt;i4'), ('f3', '&lt;f4'),
#              ('f41', '&lt;f4'), ('f42', '&lt;f4')])

print(xNewView['f41'])           # array([ 1000.,  1000.], dtype=float32)
print(xNewView['f42'])           # array([ 2000.,  2000.], dtype=float32)
</code></pre>

<p><code>xNewView</code> can then be used instead of <code>x</code>.</p>

python numpy structured-array