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 Overflow
🌐
Codedamn
codedamn.com › news › programming
Fix ValueError: could not convert string to float
November 7, 2022 - input_string = '' try: converted = float(input_string) except ValueError: converted = 0 print(converted) # 0 (as except block is executed) Code language: Python (python) This method has a huge advantage in that all three previous approaches could be used in the except block and can handle any case with ease.
🌐
Career Karma
careerkarma.com › blog › python › python valueerror: could not convert string to float solution
Python valueerror: could not convert string to float Solution | CK
December 1, 2023 - The float() method only allows you to convert strings that appear like floats. This means that you cannot convert a value if: ... A value contains non-special characters (i.e. “inf” is a special character, but “fd” is not) The “valueerror: could not convert string to float” error is raised if you fail to meet any one of the three above criteria.
🌐
Statology
statology.org › home › how to fix in pandas: could not convert string to float
How to Fix in Pandas: could not convert string to float
July 16, 2022 - #convert revenue column to float df['revenue'] = df['revenue'].apply(lambda x: float(x.split()[0].replace('$', ''))) #view updated DataFrame print(df) store revenue 0 A 400.42 1 B 100.18 2 C 243.75 3 D 194.22 #view data type of each column print(df.dtypes) store object revenue float64 dtype: object · Notice that we’re able to convert the revenue column from a string to a float and we don’t receive any error since we removed the dollar signs before performing the conversion.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-valueerror-could-not-convert-string-to-float
ValueError: could not convert string to float in Python | bobbyhadz
We only had to remove the percent sign from the string to be able to convert it to a floating-point number in the example. Note that floating-point numbers must have a period as the decimal point and not a comma.
🌐
Reddit
reddit.com › r/learnpython › valueerror: could not convert string to float
r/learnpython on Reddit: ValueError: could not convert string to float
July 23, 2022 -

I have a dollar value from a statement -52.23 and I'm simply trying to convert it to a float so I can use it in some calculations but I keep getting this error and after some research I still don't understand why.

I have the following code going through a statement pulling out each value. The values are in a csv file and the format looks like this:

07/06/2022, 07/07/2022, AMZN, Shopping, Sale, -52.23

Loop to pull the values:

with open(file, mode='r') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
        date = row[0]
        name = row[2]
        amt = float(row[5])
        category = 'misc'
        transaction = (date, name, category, amt)
        print(transaction)

Current printed result (when doing amt = row[5])

('07/06/22', 'AMZN', 'misc', '-52.23')

Update: Header of the csv file was the issue, once I skipped that row it worked.

🌐
Saturn Cloud
saturncloud.io › blog › how-to-handle-the-pandas-valueerror-could-not-convert-string-to-float
How to Handle the pandas ValueError could not convert string to float | Saturn Cloud Blog
October 19, 2023 - Finally, we convert the column to floats using the astype() function. Another approach is to employ the to_numeric() function, which can handle a variety of non-numeric characters, including special symbols. Let’s see it in action: import pandas as pd # Create a DataFrame with strings containing special characters df = pd.DataFrame({'values': ['42@', '$78', '12%', '3.14']}) # Use the `to_numeric()` function to convert the column to floats df['values'] = pd.to_numeric(df['values'], errors='coerce') # Print the DataFrame print(df)
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › how-to-handle-pandas-value-error-could-not-convert-string-to-float
How To Handle Pandas Value Error : Could Not Convert String To Float - GeeksforGeeks
July 23, 2025 - Explanation: This error occurs because the Prices column contains hyphens (-), making direct conversion to float impossible. Handling these types of errors comes under the data preprocessing phase of data analysis.
🌐
GeeksforGeeks
geeksforgeeks.org › python › cannot-convert-string-to-float-in-python
Cannot Convert String To Float in Python - GeeksforGeeks
July 23, 2025 - Below, code will raise a `ValueError` because the string "1,234.56" includes a comma as a thousand separator, making it an invalid input for converting to a float in Python. ... Hangup (SIGHUP) Traceback (most recent call last): File "Solution.py", line 3, in <module> print(float(a)) ValueError: could not convert string to float: '1,234.56'
Find elsewhere
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
ValueError: could not convert string to float: ' ' - Raspberry Pi Forums
try: intervalMin = float(intervalEntry.get()) except ValueError: intervalMin = 1 # or some other default value thanks for your responses all @thagrol @jojopi and @pcmanbob I have tried this program to apply, but the result is still the same problem ... the result is still the same problem When I run the program here with the proposed changes, then this "ValueError: could not convert string to float: ' '" does no longer appear.
🌐
ONEXT DIGITAL
onextdigital.com › home › valueerror: could not convert string to float: how to solve it in python
Valueerror: could not convert string to float: How to solve it in Python
December 8, 2022 - The float() function can only convert strings that include float-like integers. This indicates that you won’t be able to convert a value if: There are spaces in a value. A comma appears in a value.
🌐
Its Linux FOSS
itslinuxfoss.com › home › python › valueerror: could not convert string to float in python
ValueError: could not convert string to float in Python – Its Linux FOSS
November 12, 2022 - The “ValueError: could not convert string to float” occurs in Python due to the incorrect initialization of value to a string variable. The string to be converted must not contain any characters or symbols.
🌐
Python.org
discuss.python.org › python help
Value error in Python: Could not convert string to float: Male - Python Help - Discussions on Python.org
January 24, 2024 - Hi All, I hope this message finds you well. I have encountered an error and hoping is someone could assist me in getting this resolved. I attempted to make a countplot with the Gender attribute however, when executing the code, I have received, ValueError: could not convert string to float: ...
🌐
Stack Overflow
stackoverflow.com › questions › 64633461 › valueerror-could-not-convert-string-to-float-30-01-20
python - ValueError: could not convert string to float: :'30/01/20' - Stack Overflow
ValueError: could not convert string to float: '30/01/20' ... What were you expecting? this is not a floating number: '30/01/20', it's a date!
🌐
Position Is Everything
positioniseverything.net › home › could not convert string to float: fix the conversion error
Could Not Convert String to Float: Fix the Conversion Error - Position Is Everything
December 29, 2025 - Finally, for “sklearn”, use one-hot encoding for conversions between non-numeric and numeric values. To solve the “could not convert string to float python CSV” error, you can remove the spaces or non-numerics in your CSV file.
🌐
Codecademy
codecademy.com › forum_questions › 50e5a8e0c1f59740df000aee
ValueError: could not convert string to float | Codecademy
I'm getting the above error for line 20 in my code, which is perplexing as line 19 works fine with the same code (but different list). if is_rec...