0

it is showing value error for converting string into float. one of the line of my data file looks like this 100 1.2811559340137890E-003 I think maybe python can't understand E while converting. also following is my code

import math
import matplotlib.pyplot as plt
x = []
y = []
f= open('C:/Users/Dell/assignment2/error_n.dat', 'r')
for line in f:
    line= line.split(' ')

    x.append(line[0])
    y.append(line[1])
for i in range(0,4):
    x[i]=float(x[i])
    x[i]=math.log(x[i])
    y[i]=float(y[i])
    y[i]=math.log(y[i])
        

plt.plot(y, x, marker = 'o', c = 'g')

plt.show()
1
  • 1
    Always show us the full traceback message - it will indicate the exact string value that failed to be converted to a float. Commented Feb 14, 2022 at 17:15

3 Answers 3

1

The string 1.2811559340137890E-003 can be converted to float without a problem. You can easily try this in the Python shell:

>>> s = '1.2811559340137890E-003'
>>> float(s)
0.001281155934013789

However, you're actually trying to convert an empty string. See why:

>>> line = '100   1.2811559340137890E-003'
>>> line.split(' ')
['100', '', '', '1.2811559340137890E-003']

To solve your problem, simply change line.split(' ') to line.split():

>>> line.split()
['100', '1.2811559340137890E-003']
Sign up to request clarification or add additional context in comments.

Comments

0

I think the problem is that when you split that line, the second item (y) is "" (an empty string), and that's the one which can't be converted into a number.

Comments

0

float is able to handle scientific notations. However from your description, it seems like the ValueError was thrown from trying to convert empty string to float.

'100   1.2811559340137890E-003'.split(' ')

will return

['100', '', '', '1.2811559340137890E-003']

You can check the string before converting it to float to handle such error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.