Obviously some of your lines don't have valid float data, specifically some line have text id which can't be converted to float.
When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError,e:
print "error",e,"on line",i
result=stats.ttest_ind(list1,list2)
print result[1]
Answer from Anurag Uniyal on Stack Overflowpython - ValueError: could not convert string to float: id - Stack Overflow
Value error in Python: Could not convert string to float: Male
Confusing python - Cannot convert string to float
ValueError: could not convert string to float
Videos
Obviously some of your lines don't have valid float data, specifically some line have text id which can't be converted to float.
When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError,e:
print "error",e,"on line",i
result=stats.ttest_ind(list1,list2)
print result[1]
My error was very simple: the text file containing the data had some space (so not visible) character on the last line.
As an output of grep, I had 45 instead of just 45.
You need to take into account that the user might not fill in a proper value:
try:
miles = float(input("How many miles can you walk? "))
except ValueError:
print("That is not a valid number of miles")
A try/except handles the ValueError that might occur when float tries to convert the input to a float.
The problem is exactly what the Traceback log says: Could not convert string to float
- If you have a string with only numbers, python's smart enough to do what you're trying and converts the string to a float.
- If you have a string with non-numerical characters, the conversion will fail and give you the error that you were having.
The way most people would approach this problem is with a try/except (see here), or using the isdigit() function (see here).
Try/Except
try:
miles = float(input("How many miles can you walk?: "))
except:
print("Please type in a number!")
Isdigit()
miles = input("How many miles can you walk?: ")
if not miles.isdigit():
print("Please type a number!")
Note that the latter will still return false if there are decimal points in the string
EDIT
Okay, I won't be able to get back to you for a while, so I'll post the answer just in case.
while True:
try:
miles = float(input("How many miles can you walk?: "))
break
except:
print("Please type in a number!")
#All of the ifs and stuff
The code's really simple:
- It will keep trying to convert the input to a float, looping back to the beginning if it fails.
- When eventually it succeeds, it'll break from the loop and go to the code you put lower down.
I have a list of strings and I would to get the average of the list. so I need to convert those strings in the list into float but I keep getting this:
ValueError: could not convert string to float: '"104.8"\n'
How do I solve it? Thanks
I want to do some math on a dataframe but (I think) can't get one column/series into the necessary format. The column contains strings; some are '.123' while others are '0'. When I attempt the math on the column of strings by converting everything to an integer like so:
dfteam1['cloff'] = dfteam1.cloff.astype(int)
I get the following error
ValueError: invalid literal for int() with base 10: '.123'
I think it's b/c .123 isn't an integer but a float, so I change the code like so:
dfteam1['cloff'] = dfteam1.cloff.astype(float)
now I get the following error
ValueError: could not convert string to float:
I think it's b/c 0 isn't a float but an integer? Do I need to change all the 0 values to 0.00 or am I completely off base? All feedback is welcome.
THIS IS MY TASK:
Read the number list from file and convert it into an array. 2. Create a counter and set it to zero. 3. Create a for loop that traverses the number array. 4. Inside the for loop, check if the current number is less than the next number. 5. If the current number is less than the next number, decrement the counter. 6. After the for loop finishes traversing, return the counter.
THIS IS MY CODE:
with open("numbers.txt") as file:
numbers = [
float(line)
for line in file
]
count = 0
for idx, number in enumerate(numbers[:-1]):
if number < numbers[idx+1]:
count += 1
print(count)
AND THIS IS MY ERROR:
Exception has occurred: ValueError
could not convert string to float: '\n'
i really have no idea how to fix it