how do i turn an array into a special element of structured array and revert it back?

numpy provides a helper functions to do this:

>>> n, m, r = 2, 3, 4
>>> array = np.arange(n*m).reshape((n,m))
>>> import numpy.lib.recfunctions as recfunctions
>>> recfunctions.unstructured_to_structured(array, dtype=np.dtype(','.join('i'*m)))
array([(0, 1, 2), (3, 4, 5)],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4')])

And in the other direction:

>>> import numpy.lib.recfunctions as recfunctions
>>> recfunctions.structured_to_unstructured(arr2)
array([[[0, 1, 2],
        [0, 1, 2],
        [0, 1, 2],
        [0, 1, 2]],

       [[3, 4, 5],
        [3, 4, 5],
        [3, 4, 5],
        [3, 4, 5]]], dtype=int32)

In this particular case, if the original array is dtype=np.int32, you could use a view:

>>> array = np.arange(n*m, dtype=np.int32).reshape((n,m))
>>> structured_view = array.view(dtype=np.dtype(','.join('i'*m)))
>>> structured_view
array([[(0, 1, 2)],
       [(3, 4, 5)]], dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4')])

The advantage of a view is that it create a new array. Of course, this can be a disadvantage if you mutate your view and don’t expect the original array to change as well.

In the reverse, it doesn’t handle the shape you want, but you could always reshape:

>>> arr2.view(dtype=np.int32)
array([[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5, 3, 4, 5]], dtype=int32)

Using views can get tricky, fast.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top