1

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.

12
  • 2
    Why not directly use np.asarray on array_of_tuples, won't that work? Commented Sep 24, 2015 at 16:41
  • 2
    ... How did you get an array of 2-tuples in the first place? :-) Commented Sep 24, 2015 at 16:42
  • 1
    Is your "numpy array of tuples" a one-dimensional structured array, or a numpy array with dtype object, or something else? Commented Sep 24, 2015 at 16:45
  • @Divakar np.asarray gives the same output as input, cause the input is also a numpy array Commented Sep 24, 2015 at 16:48
  • I thought the input is an array of tuples! Commented Sep 24, 2015 at 16:48

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this works like a charm. I shall edit my question above to state that it is a structured array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.