I have a 2D numpy array with elements of the type np.void that are essentially tuples. Is there an efficient way to unpack the values in these tuples to a 3rd dime
In [601]: a = np.array([[(1, 2, 3), (1, 2, 3), (1, 2, 3)],
...: [(1, 2, 3), (1, 2, 3), (1, 2, 3)],
...: [(1, 2, 3), (1, 2, 3), (1, 2, 3)]],
...: dtype=[('B4', '
This is a structured array, with a compound dtype. The tuples display individual elements of the 2d array.
Recent numpy versions have added a function to conveniently convert structured arrays to unstructured:
In [606]: b=rf.structured_to_unstructured(a)
In [607]: b
Out[607]:
array([[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]], dtype=uint16)
In [608]: b[:,:,1]
Out[608]:
array([[2, 2, 2],
[2, 2, 2],
[2, 2, 2]], dtype=uint16)
a has 3 fields. Individual fields can be accessed by name:
In [610]: a['B4']
Out[610]:
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]], dtype=uint16)
That means you could construct the 3d array by concatenating the 3 individual fields:
np.stack([a['B4'],a['B3'],a['B2']])
This is like your last solution, but without the i,j iteration.
The view approach in the other answer works in this case because all fields have the same dtype,
import numpy.lib.recfunctions as rf
The rf.structured_to_unstructured works in more general cases where view does not, such as a mix of dtypes, (e.g. floats and integers).