javadba javadba - 18 days ago 7
Python Question

Converting a List of Tuples to numpy array results in single dimension

We have a list of tuples in the form (year, value):

splist

[(2002, 10.502535211267606),
(2003, 10.214794520547946),
(2004, 9.8115789473684227),
..
(2015, 9.0936585365853659),
(2016, 9.2442725379351387)]


The intention is to convert the list of tuples to a two-D numpy array. However the published answers that use
np.asarray
retain a single dimension:

dt = np.dtype('int,float')
spp = np.asarray(splist,dt)

spp
array([(2002, 10.502535211267606), (2003, 10.214794520547946),
(2004, 9.811578947368423), (2005, 9.684155844155844),
..
(2014, 9.438987341772153), (2015, 9.093658536585366),
(2016, 9.244272537935139)],
dtype=[('f0', '<i8'), ('f1', '<f8')])


This becomes clear when viewing the dimensions of the output:

In [155]: spp.shape
Out[155]: (15,)


What we wanted:

array([[(2002, 10.502535211267606)],
[(2003, 10.214794520547946)],
..
[(2014, 9.438987341772153)],
[(2015, 9.093658536585366)],
[(2016, 9.244272537935139)]])


So what is the magic to convert the list of tuples to a two dimensional array?

Answer

If I understand your desired output correctly, you can use numpy.reshape

>>> spp = np.asarray(splist, dt)
>>> spp
array([(2002, 10.502535211267606),
       (2003, 10.214794520547946),
       (2004, 9.811578947368423),
       (2015, 9.093658536585366),
       (2016, 9.244272537935139)], 
      dtype=[('f0', '<i4'), ('f1', '<f8')])

>>> np.reshape(spp, (spp.size, 1))
array([[(2002, 10.502535211267606)],
       [(2003, 10.214794520547946)],
       [(2004, 9.811578947368423)],
       [(2015, 9.093658536585366)],
       [(2016, 9.244272537935139)]], 
      dtype=[('f0', '<i4'), ('f1', '<f8')])
Comments