Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert "[nan,1,2,3]" string to list [nan,1,2,3]?

How can I convert "[nan,1,2,3]" string to list [nan,1,2,3]?

If I use

    from ast import literal_eval

    literal_eval("[1,2,3]")

I get

    [1, 2, 3]

But if i try to convert the string with a nan in it, i get the following error occurred:

    File "<unknown>", line 1
        [nan  1  2  3
           ^
    SyntaxError: invalid syntax

    Process finished with exit code 1
like image 930
Shouheng Zhang Avatar asked Dec 31 '22 10:12

Shouheng Zhang


1 Answers

Try using np.fromstring

Ex:

import numpy as np

lst = '[nan  1  2  3]'
print(np.fromstring(lst.strip("[]"), sep=' '))
#-->[nan  1.  2.  3.]
like image 111
Rakesh Avatar answered Jan 03 '23 00:01

Rakesh