Alina Nicolae - 1 year ago 94

Python Question

I want to declare a numpy array (

`arr`

`dt1 = np.dtype([('sec', '<i8'), ('nsec', '<i8')])`

dt2 = np.dtype([('name', 'S10'), ('value', '<i4')])

arr = np.array([('x', dtype=dt1), ('y', dtype=dt2)])

The structure is something like this:

`arr['x'] = elements with the format dt1 (sec and nsec)`

arr['y'] = array of n elements with the format dt2 (name and value)

And the elements within should be accessed like this:

`arr['x']['sec'], arr['x']['nsec'], arr['y'][0]['name'] etc.`

But I get an

`invalid syntax`

What is the correct syntax in this situation?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

A doubly compound dtype might work:

```
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))
```

A dictionary would work with similar syntax

```
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'
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**