Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convertin string of list to list of floats [pandas]

when importing in pandas the data looks like that:

>>> BOM.PriceQty['substrate']
'[200.0, 300.0, 500.0]'

how do I convert it to list of floats? tried convert_objact:

>>> BOM.PriceQty['substrate'].convert_object(convert_numeric=True)

Traceback (most recent call last): File "", line 1, in AttributeError: 'str' object has no attribute 'convert_object'

Thanks!

like image 712
Shuki Avatar asked Feb 09 '16 09:02

Shuki


1 Answers

This would nicely convert a string representing a list of floats to an actual list of floats:

s = '[200.0, 300.0, 500.0]'
l = [float(x.strip(' []')) for x in s.split(',')]

The strip function removes any ' ', '[', and ']' characters resulting from the split.

Result:

In [1]: l
Out[1]: [200.0, 300.0, 500.0]

If you want to apply this transformation to the entire column, apply it as a lambda function:

BOM.PriceQty.apply(lambda s: [float(x.strip(' []')) for x in s.split(',')])
like image 200
IanS Avatar answered Sep 28 '22 16:09

IanS