从平面列表创建结构化数组

时间:2014-03-07 19:41:34

标签: numpy multidimensional-array

假设我有一个像这样的单一列表L

In [97]: L
Out[97]: [2010.5, 1, 2, 3, 4, 5]

...我希望得到一个像这样的结构化数组:

array((2010.5, [1, 2, 3, 4, 5]),
      dtype=[('A', '<f4'), ('B', '<u4', (5,))])

如何才能最有效地进行此转化?我可以直接将后一种dtype传递给array(L, ...)array(tuple(L))

In [98]: dtp                                                                                                                                                                                 [9/1451]
Out[98]: [('A', '<f4', 1), ('B', '<u4', 5)]

In [99]: array(L, dtp)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-99-32809e0456a7> in <module>()
----> 1 array(L, dtp)

TypeError: expected an object with a buffer interface
In [101]: array(tuple(L), dtp)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-101-4d0c49a9f01d> in <module>()
----> 1 array(tuple(L), dtp)

ValueError: size of tuple must match number of fields.

的工作原理是传递一个临时dtype,其中每个字段都有一个条目,然后用我真正想要的dtype查看:

In [102]: tdtp
Out[102]: 
[('a', numpy.float32),
 ('b', numpy.uint32),
 ('c', numpy.uint32),
 ('d', numpy.uint32),
 ('e', numpy.uint32),
 ('f', numpy.uint32)]

In [103]: array(tuple(L), tdtp).view(dtp)
Out[103]: 
array((2010.5, [1, 2, 3, 4, 5]), 
      dtype=[('A', '<f4'), ('B', '<u4', (5,))])

但是创建这个临时dtype是我想要尽可能避免的额外步骤。

是否可以直接从我的平面列表转到我的结构化dtype,而不使用上面显示的中间dtype?

(注意:在我的实际用例中,我有一个读取例程,读取自定义文件格式和每个条目的许多值;所以我宁愿避免我需要构建临时和实际dtype的情况手工。)

1 个答案:

答案 0 :(得分:4)

不是将tuple(L)传递给array,而是传递一个带有与dtype嵌套匹配的嵌套值的参数。对于您展示的示例,您可以传递(L[0], L[1:])

In [28]: L
Out[28]: [2010.5, 1, 2, 3, 4, 5]

In [29]: dtp
Out[29]: [('A', '<f4', 1), ('B', '<u4', 5)]

In [30]: array((L[0], L[1:]), dtype=dtp)
Out[30]: 
array((2010.5, [1L, 2L, 3L, 4L, 5L]), 
      dtype=[('A', '<f4'), ('B', '<u4', (5,))])