1

I am working on csv file and the numbers are very small and it's cast as a string, when I try to cast it as a float i got the following error:

ValueError: could not convert string to float: '"1.0000000000000000E-02"'

here's the code:

x = float(df['frequency'].iloc[0])

I don't know why as I think E indicates the power here not just a string, any solution?

Vishesh Mangla
  • 664
  • 9
  • 20
Mee
  • 1,413
  • 5
  • 24
  • 40

2 Answers2

1

I think the reason you got ValueError was due to multiple quotes in a string. However if your data is returning the string in that form, the best way to convert would include some string handling and then using a float() function.

You can use eval() function to get that:

a=eval('"1.0000000000000000E-02"')
float(a)

So your code would look something like :

x=float(eval(df['frequency'].iloc[0]))
Raghav Gupta
  • 454
  • 3
  • 12
0

Use "1.0000000000000000E-02" not '"1.0000000000000000E-02"'. In your case you were storing a string with " as a character. Clearly " has no integer representation and thus you received an error from the python interpreter.

It is difficult to comment what the error might be without seeing the csv but most probably you would have written these numbers as "1.000E-12" in the csv and reading them as str makes them '"1.000E-12"' treating " as a character. You can do df['frequency'].apply(lambda x:x[1:-1]) to remove ".

Alternatively pandas.read_csv(data, quotechar='"') can be used too. Stackoverflow post

Alternatively pandas.read_csv(data, doublequote=True) can be used too See the docs Read Csv Docs

>>> s ="1.0000000000000000E-02"
>>> float(s)
0.01

>>> s ='"1.0000000000000000E-02"'
>>> float(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '"1.0000000000000000E-02"'
Vishesh Mangla
  • 664
  • 9
  • 20