[英]how to set dtype for nested numpy ndarray?
我正在研究以下數據結構,從中試圖創建一個包含所有數據的ndarray:
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。
先感謝您!
如果響應數組是固定長度的,我可以使它起作用(也許Numpy必須能夠預先計算結構化數組中每個記錄的大小?)。 如Numpy手冊頁中針對結構化數組所述 ,您可以為結構化數組中的字段指定形狀。
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)])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.