2013-10-05 51 views
0

我在下面的數據結構,從中我想創建一個ndarray工作包含所有數據:如何設置嵌套numpy ndarray的dtype?

 instrument   filter    response 
----------------------------------------------------- 
     spire    250um   array of response 
     ...    ...    ... 

where the array of response is: 
     linenumber  wavelangth  throughput 
----------------------------------------------------- 
     0  1.894740e+06   0.000e+00 
     1  2.000000e+06   1.000e-02 
     2  2.026320e+06   3.799e-02 
     ...    ....    .... 

所以,我希望我可以把數據發送到一個ndarray,通過使用下面的代碼:

import numpy as np 

data = [('spire', '250um', [(0, 1.89e6, 0.0), (1,2e6, 1e-2), (2,2.02e6,3.8e-2), ...]), 
     ('spire', '350', [ (...), (...), ...]), 
     ..., 
     ] 
table = np.array(data, dtype=[('instrument', '|S32'), 
           ('filter', '|S64'), 
           ('response', [('linenumber', 'i'), 
              ('wavelength', 'f'), 
              ('throughput', 'f')]) 
           ]) 

此代碼引發異常,因爲有list(tuple, list(tuple))模式。改變後的data到:

data = [('spire', '250um', np.array([(0, 1.89e6, 0.0), (1,2e6, 1e-2), (2,2.02e6,3.8e-2), ...], 
            dtype=[('linenumber','i'), ('wavelength','f'), ('throughput','f')])), 
     ('spire', '350', np.array([ (...), (...), ...],dtype=[...])), 
     ..., 
     ]] 

然後代碼可以運行通過,但是,結果因爲對於response字段,只有響應的陣列的第一個條目被取是錯誤的:

>>print table[0] 

('spire', '250um', (0,1.89e6,0.0)) 

而不是整個陣列。

我的問題是,如何正確設置dtype關鍵字來使這項工作?在這兩種情況下:1.包含元組列表的元組的嵌套列表; 2.包含非同類ndarray的元組的嵌套列表。

預先感謝您!

回答

1

如果響應數組是固定長度的(也許Numpy必須能夠預先計算結構化數組中每條記錄的大小?),我可以得到這個工作。如the Numpy manual page for structured arrays所述,您可以指定結構化數組中字段的形狀。

import numpy as np 

data = [('spire', '250um', [(0, 1.89e6, 0.0), (1, 2e6, 1e-2)]), 
     ('spire', '350', [(0, 1.89e6, 0.0), (2, 2.02e6, 3.8e-2)]) 
     ] 
table = np.array(data, dtype=[('instrument', '|S32'), 
           ('filter', '|S64'), 
           ('response', [('linenumber', 'i'), 
              ('wavelength', 'f'), 
              ('throughput', 'f')], (2,)) 
           ]) 

print table[0] 
# gives ('spire', '250um', [(0, 1890000.0, 0.0), (1, 2000000.0, 0.009999999776482582)]) 
+0

謝謝,它的工作原理。我剛剛想出了另一種方式,這不如你的方式:將'response'的dtype設置爲'object',它將採用'data'中定義的ndarray。我的解決方案使我無法按列方式訪問數據,而您的方法則不能。 –