我想声明一个具有特定格式的元素的numpy数组(arr
),如下所示:
dt1 = np.dtype([('sec', '<i8'), ('nsec', '<i8')])
dt2 = np.dtype([('name', 'S10'), ('value', '<i4')])
arr = np.array([('x', dtype=dt1), ('y', dtype=dt2)])
结构是这样的:
arr['x'] = elements with the format dt1 (sec and nsec)
arr['y'] = array of n elements with the format dt2 (name and value)
并且其中的元素应按以下方式访问:
arr['x']['sec'], arr['x']['nsec'], arr['y'][0]['name'] etc.
但是我收到一个
invalid syntax
错误。在这种情况下正确的语法是什么?
最佳答案
双重复合dtype可能有效:
In [834]: dt1 = np.dtype([('sec', '<i8'), ('nsec', '<i8')])
...: dt2 = np.dtype([('name', 'S10'), ('value', '<i4')])
...:
In [835]: dt = np.dtype([('x', dt1),('y', dt2)])
In [837]: z=np.ones((3,), dtype=dt)
In [838]: z
Out[838]:
array([((1, 1), (b'1', 1)), ((1, 1), (b'1', 1)), ((1, 1), (b'1', 1))],
dtype=[('x', [('sec', '<i8'), ('nsec', '<i8')]), ('y', [('name', 'S10'), ('value', '<i4')])])
In [839]: z['x']['sec']
Out[839]: array([1, 1, 1], dtype=int64)
In [841]: z['y'][0]['name']='y0 name'
In [842]: z
Out[842]:
array([((1, 1), (b'y0 name', 1)), ((1, 1), (b'1', 1)), ((1, 1), (b'1', 1))],
dtype=[('x', [('sec', '<i8'), ('nsec', '<i8')]), ('y', [('name', 'S10'), ('value', '<i4')])])
In [843]: z[0]
Out[843]: ((1, 1), (b'y0 name', 1))
字典可以使用类似的语法
In [845]: d={'x':np.ones((3,),dt1), 'y':np.zeros((4,),dt2)}
In [846]: d
Out[846]:
{'x': array([(1, 1), (1, 1), (1, 1)],
dtype=[('sec', '<i8'), ('nsec', '<i8')]),
'y': array([(b'', 0), (b'', 0), (b'', 0), (b'', 0)],
dtype=[('name', 'S10'), ('value', '<i4')])}
In [847]: d['y'][0]['name']='y0 name'