【问题标题】:how to set dtype for nested numpy ndarray?如何为嵌套的 numpy ndarray 设置 dtype?
【发布时间】:2013-10-05 19:35:28
【问题描述】:

我正在研究以下数据结构,我试图从中创建一个包含所有数据的 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字段,只取response数组的第一项:

>>print table[0]

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

而不是整个数组。

我的问题是,如何正确设置 dtype 关键字以使其工作?在这两种情况下: 1. 嵌套的元组列表,其中包含元组列表; 2.一个嵌套的元组列表,其中包含一个不均匀的ndarray。

提前谢谢你!

【问题讨论】:

    标签: python numpy multidimensional-array recarray


    【解决方案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)])
    

    【讨论】:

    • 谢谢,它有效。我只是想出了另一种方法,它不如你的方法:将response的dtype设置为object,这将采用data中定义的ndarray。我的解决方案禁止我按列访问数据,而您的则没有。
    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2019-06-27
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    相关资源
    最近更新 更多