Luke Vincent February 2016

Convert list in String format back to list of float numbers

str = [  3.82133931e-01   4.27354313e-02   1.94678816e-03   0.00000000e+00
   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
   0.00000000e+00   3.61185198e-06   1.26606241e-01   1.18472360e-01]

The above string has been retrieved from a database text field and I'm trying to convert it back into a list of floats however no matter what I try I can't seem to get rid of the square brackets.

floatList = []

for k, v in enumerate(str.split('   ')):
    if re.search(r'\d', v):
        item = re.sub(r'\D\S', '', v).rstrip()
        item = re.sub(r'\[.*?\]/g', '', item)
        floatList.append(float(item))

I have tried:

item.replace('[', '')
item.replace(']', '')

and with the Ascii codes.

Always the error ValueError: could not convert string to float: '[ 536444501'

Answers


mgilson February 2016

It seems like you should be able to just strip off the [ and ]:

str = str.replace('[', '').replace(']', '')

And then split the string calling float on each member of the split string:

floats = [float(x) for x in str.split()]

Notice that because python strings are immutable, things like:

str.replace('[', '')

Doesn't change str in place. Instead, it returns a new string with the requested characters removed. Since it returns a new string, we need to give that string a name (I just chose to give it the name str1 again to avoid using too many names...)

1Note that str is also not a good name for a variable since it shadows the builtin str type. I would highly recommend picking a different name :-)


Jake Cobb February 2016

How about this:

floats = [ float(x) for x in re.findall('\d+\.\d+e[+\-]\d\d', str)]


Sayse February 2016

You should be storing your numbers in your database as floats rather than strings.

If you're using postgres you can make use of the ArrayField

from django.contrib.postgres.fields import ArrayField
my_floats = ArrayField(models.FloatField())

If you're not, you should still store them as numbers but it may require a different relational model.

Post Status

Asked in February 2016
Viewed 3,959 times
Voted 10
Answered 3 times

Search




Leave an answer