How To Convert A Np Array Of Lists To A Np Array
latest updated: >>> a = np.array(['0,1', '2,3', '4,5']) >>> a array(['0,1', '2,3', '4,5'], dtype='|S3') >>> b = np.core.defchararray.split(a, sep=',') &g
Solution 1:
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')
Solution 2:
Suggestion in comments works fine for me.
arr = np.array([list(['0', '1']), list(['2', '3']), list(['4', '5'])], dtype=object)
res = np.array(arr).astype(float)
print(res, res.dtype, res.shape)
# [[ 0. 1.]# [ 2. 3.]# [ 4. 5.]] float64 (3, 2)
Post a Comment for "How To Convert A Np Array Of Lists To A Np Array"