pythonnumpynumpy-dtype

How to create a numpy dtype from other dtypes?


I normally create numpy dtypes like this:

C = np.dtype([('a',int),('b',float)])

However in my code I also use the fields a and b individually elsewhere:

A = np.dtype([('a',int)])
B = np.dtype([('b',float)])

For maintainability I'd like to derive C from types A and B somehow like this:

C = np.dtype([A,B])    # this gives a TypeError

Is there a way in numpy to create complex dtypes by combining other dtypes?


Solution

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

    In [44]: A = np.dtype([('a',int)])
    
    In [45]: A.descr
    Out[45]: [('a', '<i8')]
    
    In [46]: B = np.dtype([('b',float)])
    
    In [47]: B.descr
    Out[47]: [('b', '<f8')]
    

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

    In [48]: C = np.dtype(A.descr + B.descr)
    
    In [49]: C
    Out[49]: dtype([('a', '<i8'), ('b', '<f8')])