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

2024/7/8 6:36:29

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.

Answer

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')
https://en.xdnf.cn/q/120397.html

Related Q&A

Regex stemmer code explanation

Can someone please explain what does this code do?def stemmer(word):[(stem,end)] = re.findall(^(.*ss|.*?)(s)?$,word)return stem

Scraping data from a dynamic web database with Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 9…

Python representation of floating point numbers [duplicate]

This question already has answers here:Floating Point Limitations [duplicate](3 answers)Closed 10 years ago.I spent an hour today trying to figure out whyreturn abs(val-desired) <= 0.1was occasional…

How to grep only duplicate key:value pair in python dictionary?

I have following python dictionary.a={name:test,age:26,place:world,name:test1}How to grep only duplicate key:value pair from the above?Output should be: "name: test and name:test1"

IndentationError - expected an indented block [duplicate]

This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 7 months ago.I get the IndentationError: expected an indented block. I was tryi…

No axis named 1 for object type class pandas.core.frame.DataFrame

I created a DataFrame and I am trying to sort it based on the columns. I used the below code.frame.sort_index(axis=1)But this is causing the below errors------------------------------------------------…

str.replace with a variable

This is probably a simple fix, but having a little trouble getting my head around it; Im reading lines from a different script, and want to replace a line with a variable, however it replaces it with b…

How to generate DTD from XML?

Can a DTD be generated from an XML file using Python?

I have a very big list of dictionaries and I want to sum the insides

Something like{A: 3, 45, 34, 4, 2, 5, 94, 2139, 230345, 283047, 230847}, {B: 92374, 324, 345, 345, 45879, 34857987, 3457938457), {C: 23874923874987, 2347}How can I reduce that to {A: 2304923094820398},…

How to debug a TypeError no attribute __getitem__? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 10 years ago.Improv…