MarkNS
MarkNS

Reputation: 4021

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:

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')])

Upvotes: 3

Views: 1300

Answers (1)

MSeifert
MSeifert

Reputation: 152587

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

Upvotes: 5

Related Questions