Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

python - 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=',')
>>> 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 "<stdin>", line 1, in <module>
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:

enter image description here

thx for your suggestions but I cannot find the difference.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...