Home > Software engineering >  How to convert 1D numpy array of tuples to 2D numpy array?
How to convert 1D numpy array of tuples to 2D numpy array?

Time:02-03

I have a numpy array of tuples:

import numpy as np
the_tuples = np.array([(1, 4), (7, 8)], dtype=[('f0', '<i4'), ('f1', '<i4')])

I would like to have a 2D numpy array instead:

the_2Darray = np.array([[1,4],[7,8]])

I have tried doing several things, such as

import numpy as np
the_tuples = np.array([(1, 4), (7, 8)], dtype=[('f0', '<i4'), ('f1', '<i4')])
the_2Darray = np.array([*the_tuples])

How can I convert it?

CodePudding user response:

Needed to add the_tuples.astype(object).

import numpy as np
the_tuples = np.array([(1, 4), (7, 8)], dtype=[('f0', '<i4'), ('f1', '<i4')])
the_tuples = the_tuples.astype(object)
the_2Darray = np.array([*the_tuples])

CodePudding user response:

This is a structured array - 1d with a compound dtype:

In [2]: arr = np.array([(1, 4), (7, 8)], dtype=[('f0', '<i4'), ('f1', '<i4')])

In [3]: arr.shape, arr.dtype
Out[3]: ((2,), dtype([('f0', '<i4'), ('f1', '<i4')]))

recfunctions has a function designed to do such a conversion:

In [4]: import numpy.lib.recfunctions as rf

In [5]: arr1 = rf.structured_to_unstructured(arr)    
In [6]: arr1
Out[6]: 
array([[1, 4],
       [7, 8]])

view works if all fields have the same dtype, but the shape isn't kept well:

In [7]: arr.view('int')
Out[7]: array([1, 4, 7, 8])

The tolist produces a list of tuples (instead of a list of lists):

In [9]: arr.tolist()
Out[9]: [(1, 4), (7, 8)]

Which can be used as the basis for making a new array:

In [10]: np.array(arr.tolist())
Out[10]: 
array([[1, 4],
       [7, 8]])

Note that when you created the array (in [2]) you had to use the list of tuples format.

  • Related