[Solved] how to convert a np array of lists to a np array


I was wondering how you got the array of lists. That usually takes some trickery.

In [2]: >>> a = np.array(["0,1", "2,3", "4,5"])
   ...: >>> b = np.core.defchararray.split(a, sep=',')
   ...: 
In [4]: b
Out[4]: array([list(['0', '1']), list(['2', '3']), list(['4', '5'])], dtype=object)

Simply calling array again doesn’t change things:

In [5]: np.array(b)
Out[5]: array([list(['0', '1']), list(['2', '3']), list(['4', '5'])], dtype=object)

stack works – it views b as a list of elements, in this case lists, and joins them on a new axis

In [6]: np.stack(b)
Out[6]: 
array([['0', '1'],
       ['2', '3'],
       ['4', '5']], dtype="<U1")
In [7]: np.stack(b).astype(float)
Out[7]: 
array([[0., 1.],
       [2., 3.],
       [4., 5.]])

But your ‘old’ case was a 2d array of lists. This stack trick does not work, at least not directly.

In [8]: a = np.array(["0,1", "2,3", "4,5","6,7"]).reshape(2,2)
In [9]: b = np.core.defchararray.split(a, sep=',')
In [11]: np.stack(b)
Out[11]: 
array([[list(['0', '1']), list(['2', '3'])],
       [list(['4', '5']), list(['6', '7'])]], dtype=object)

In [12]: np.stack(b.ravel())
Out[12]: 
array([['0', '1'],
       ['2', '3'],
       ['4', '5'],
       ['6', '7']], dtype="<U1")

or

In [13]: np.array(b.tolist())
Out[13]: 
array([[['0', '1'],
        ['2', '3']],

       [['4', '5'],
        ['6', '7']]], dtype="<U1")

solved how to convert a np array of lists to a np array