如何为嵌套的numpy ndarray设置dtype?

2024-05-19 02:50:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理以下数据结构,我试图从中创建一个包含所有数据的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:

^{pr2}$

此代码引发异常,因为存在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一种嵌套的元组列表,其中包含不均匀的数组。在

提前谢谢你!在


Tags: of数据代码列表response数组arraylist
1条回答
网友
1楼 · 发布于 2024-05-19 02:50:12

如果响应数组的长度是固定的(也许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)])

相关问题 更多 >

    热门问题