Shuki
Shuki

Reputation: 97

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!

Upvotes: 5

Views: 6077

Answers (2)

Loony_D
Loony_D

Reputation: 41

You can use literal eval as follows:

from ast import literal_eval

BOM.PriceQty['substrate'] = BOM.PriceQty['substrate'].apply(lambda x: literal_eval(str(x)))

str(x) is an added protection to avoid exceptions if the input data is a list. You can remove it if the column value is always a string

Upvotes: 0

IanS
IanS

Reputation: 16251

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(',')])

Upvotes: 5

Related Questions