If someone could help with this, I'd be very grateful as it's been driving me a bit crazy for a couple of hours!
I have an ndarray as follows:
array([[[0, 0],
[0, 2],
[0, 4]],
[[1, 0],
[1, 2],
[1, 4]]])
I would like to convert this to a record array:
array([[(0, 0),
(0, 2),
(0, 4)],
[(1, 0),
(1, 2),
(1, 4)]],
dtype=[('x', '<i4'), ('y', '<i4')])
You can simply use .view
to "change" the dtype and .reshape
to "remove" the last dimension:
>>> import numpy as np
>>> arr = np.array([[[0, 0], [0, 2], [0, 4]],
... [[1, 0], [1, 2], [1, 4]]])
>>> newarr = arr.view(dtype=np.dtype([('x', 'i4'), ('y', 'i4')]))
>>> newarr = newarr.reshape(newarr.shape[:-1])
>>> newarr
array([[(0, 0), (0, 2), (0, 4)],
[(1, 0), (1, 2), (1, 4)]],
dtype=[('x', '<i4'), ('y', '<i4')])
Note that you have to be careful with .view
, hardcoding the dtype might be not "safe" here. But you can simply reuse the current dtype:
>>> newarr = arr.view(dtype=np.dtype([('x', arr.dtype), ('y', arr.dtype)]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.