2

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?

3 Answers 3

4

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')])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Your method is more concise than mine using list concatenations.
4

According to dtype documentation, dtypes have an attribute descr which provides an "Array-interface compliant full description of the data-type". Therefore:

A = np.dtype([('a',int)])    # A.descr -> [('a', '<i4')]
B = np.dtype([('b',float)])  # B.descr -> [('b', '<f8')]
# then
C = np.dtype([A.descr[0], B.descr[0]])

1 Comment

Heh, darn near simultaneous answers. :)
0

There is a backwater module in numpy that has a bunch of structured/rec array utilities.

zip_descr does this sort of descr concatenation, but it starts with arrays rather than the dtypes:

In [77]: import numpy.lib.recfunctions as rf
In [78]: rf.zip_descr([np.zeros((0,),dtype=A),np.zeros((0,),dtype=B)])
Out[78]: [('a', '<i4'), ('b', '<f8')]
In [81]: rf.zip_descr([np.array((0,),dtype=A),np.array((0,),dtype=B)])
Out[81]: [('a', '<i4'), ('b', '<f8')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.