5

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!

EdChum
  • 376,765
  • 198
  • 813
  • 562
Shuki
  • 97
  • 1
  • 3
  • 8
  • it already looks like a list of floats, what does `type(BOM.PriceQty['substrate'][0])` show? – EdChum Feb 09 '16 at 09:18
  • 1
    It seems like a string representing a list, in that case you have to evaluate the string: `eval(BOM.PriceQty['substrate'])` – joris Feb 09 '16 at 09:24
  • 1
    It's a string that looks like a list of floats. The quick&dirty solution would be to pass the string to `eval`. However, [it may not be a good idea to do that](http://stackoverflow.com/q/1832940/3005167). – MB-F Feb 09 '16 at 09:24
  • type(BOM.PriceQty['substrate'][0]) shows – Shuki Feb 09 '16 at 14:02

2 Answers2

5

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(',')])
IanS
  • 15,771
  • 9
  • 60
  • 84
0

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

Loony_D
  • 31
  • 5