How to create a numpy dtype from other dtypes?
<p>I normally create numpy dtypes like this:  </p>

<pre><code>C = np.dtype([('a',int),('b',float)])
</code></pre>

<p>However in my code I also use the fields <code>a</code> and <code>b</code> individually elsewhere:  </p>

<pre><code>A = np.dtype([('a',int)])
B = np.dtype([('b',float)])
</code></pre>

<p>For maintainability I'd like to derive <code>C</code> from types <code>A</code> and <code>B</code> somehow like this:  </p>

<pre><code>C = np.dtype([A,B])    # this gives a TypeError
</code></pre>

<p>Is there a way in numpy to create complex dtypes by combining other dtypes?</p>

<p>You can combine the fields using the <code>.descr</code> attribute of the dtypes.  For example, here are your <code>A</code> and <code>B</code>.  Note that the <code>.descr</code> attrbute is a list containing an entry for each field:</p>

<pre><code>In [44]: A = np.dtype([('a',int)])

In [45]: A.descr
Out[45]: [('a', '&lt;i8')]

In [46]: B = np.dtype([('b',float)])

In [47]: B.descr
Out[47]: [('b', '&lt;f8')]
</code></pre>

<p>Because the values of the <code>.descr</code> attributes are lists, they can be added to create a new dtype:</p>

<pre><code>In [48]: C = np.dtype(A.descr + B.descr)

In [49]: C
Out[49]: dtype([('a', '&lt;i8'), ('b', '&lt;f8')])
</code></pre>

python numpy numpy-dtype