Reputation: 465
I have a one-dimensional structured array e.g.([ (1,2), (3,4) ]) and want to convert it to 2D numpy array ([ [1,2], [3,4] ]). Right now I am using list comprehension and then np.asarray()
list_of_lists = [list(elem) for elem in array_of_tuples]
array2D = np.asarray(list_of_lists)
This doesn't look very efficient - is there a better way? Thanks.
NOTE: the initial version of this question was mentioning "numpy array of tuples" instead of one-dimensional structured array. This might be useful for confused python newbies as me.
Upvotes: 1
Views: 408
Reputation: 114781
In a comment, you stated that the array is one-dimensional, with dtype [('x', '<f4'), ('y', '<f4'), ('z', '<f4'), ('confidence', '<f4'), ('intensity', '<f4')]
. All the fields in the structured array are the same type ('<f4'
), so you can create a 2-d view using the view
method:
In [13]: x
Out[13]:
array([(1.0, 2.0, 3.0, 4.0, 5.0), (6.0, 7.0, 8.0, 9.0, 10.0)],
dtype=[('x', '<f4'), ('y', '<f4'), ('z', '<f4'), ('confidence', '<f4'), ('intensity', '<f4')])
In [14]: x.view('<f4').reshape(len(x), -1)
Out[14]:
array([[ 1., 2., 3., 4., 5.],
[ 6., 7., 8., 9., 10.]], dtype=float32)
In this case, the view
method gives a flattened result, so we have to reshape it into a 2-d array using the reshape
method.
Upvotes: 3