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=',')
>>> b
array([list(['0', '1']), list(['2', '3']), list(['4', '5'])], dtype=object)
>>> c = np.array(b).astype(float)
Traceback (most recent call last):
File "", line 1, in
ValueError: setting an array element with a sequence.
old:
I have a np array like this:
array([[list(['3', '6']), list(['2', '1'])],
[list(['0', '7']), list(['1', ' 9'])]], dtype=object)
I want to convert it to a np array of string like this:
array([[['3', '6'], ['2', '1']],
[['0', '7'], ['1', ' 9']]], dtype=object)
so that I can use astype("float32") to directly convert it to a float array.
any idea?
old update:
thx for your suggestions but I cannot find the difference.
解决方案
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='
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='
or
In [13]: np.array(b.tolist())
Out[13]:
array([[['0', '1'],
['2', '3']],
[['4', '5'],
['6', '7']]], dtype='