[英]Convert last dimension of ndarray to tuple/recarray
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: 我有一个ndarray如下:
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: 你可以简单地使用.view
来“改变” .reshape
和.reshape
来“删除”最后一个维度:
>>> 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. 请注意,你必须小心.view
,硬编码dtype在这里可能不是“安全”。 But you can simply reuse the current dtype: 但您可以简单地重用当前的dtype:
>>> newarr = arr.view(dtype=np.dtype([('x', arr.dtype), ('y', arr.dtype)]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.