Search code examples
pythondataset

Python converting string "1+2" to float


I'm beginner with Python, and I have problem with reading data from table.

Program can't convert string that contains addition of two numbers to float.

I get error could not convert string to float: '6.8 + 3.9'

I'm converting with this command

df['ScreenSize'].astype(np.float)

Is there any way to fix this?


Solution

  • The eval function would be a perfect solution here. If you write eval(df['ScreenSize'].astype(str), then python will attempt to treat the value returned by df['ScreenSize'] as a python expression and evaluate it. If successful, the eval function will return the result.