2016-09-14 107 views
2

我通常創建numpy的dtypes這樣的:如何從其他dtypes創建numpy dtype?

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

但是在我的代碼我也使用的字段ab單獨的估算:

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

可維護性我想從類型派生CAB莫名其妙如此:

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

numpy有沒有方法通過組合其他dtype來創建複雜的dtype?

回答

3

您可以使用dtypes的.descr屬性組合字段。例如,這裏是您的AB。需要注意的是.descr attrbute是包含每個字段中輸入列表:

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')] 

因爲.descr屬性的值是列表,可以將它們加入到創建一個新的D型:

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

In [49]: C 
Out[49]: dtype([('a', '<i8'), ('b', '<f8')]) 
+0

謝謝!你的方法比使用列表連接更簡潔。 – hazrmard

4

根據到dtype documentation,dtypes有一個屬性descr,它提供了「數組類型接口符合數據類型的完整描述」。因此:

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]]) 
+0

嘿,靠近同時答案。 :) –

0

有一個在一個numpy回水模塊,其具有一串結構/ REC陣列實用程序。

zip_descr做這種descr拼接的,但它開始使用數組,而不是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')]