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
🌐
GeeksforGeeks
geeksforgeeks.org › python › cannot-convert-string-to-float-in-python
Cannot Convert String To Float in Python - GeeksforGeeks
July 23, 2025 - The "Cannot Convert String to Float" error in Python typically occurs when attempting to convert a string to a float data type, but the string content is not a valid numeric representation.
🌐
Python.org
discuss.python.org › python help
Could not convert string to float - Python Help - Discussions on Python.org
January 6, 2022 - Hi! I have a “txt” file, which has several numbers like this: 1 2 3 4 I want my programme to sum all of them. I’ve done the following: file=open(“n38.txt”, “r”) result=0 for line in file: n=float(line) print(n) result=result+n print(“the sum is”, result) But I get the mistake: "ValueError: could not convert string to float: ‘1\n’. Where is the mistake?
🌐
Codedamn
codedamn.com › news › programming
Fix ValueError: could not convert string to float
November 7, 2022 - This error is encountered if we intend to convert a string that cannot be converted to the float() data type. This kind of conversion is not supported till the latest version of Python i.e. 3.10.7. . We face this issue in various places: ... ...
🌐
Python.org
discuss.python.org › python help
Could not convert string to float: '' - Python Help - Discussions on Python.org
June 6, 2024 - Hi to everybody, In pandas I want to convert a string column in a float one, but I get all the time the same error message: could not convert string to float: ‘’ The content of this column is the following: 2019-08-06T16:47:07.508 So I replaced “-”, “T”, “:” and “.” with following code: climbing[“UTC time”] = climbing[“UTC time”].replace(“-”, “”, regex=True) climbing[“UTC time”] = climbing[“UTC time”].replace(“:”, “”, regex=True) climbing[“UTC time”] = climbing[“UTC time”].replace(“.”, “”,...
🌐
Reddit
reddit.com › r/learnpython › python pandas - can't convert string to float (i think b/c of multiple data types in column...)
r/learnpython on Reddit: Python pandas - can't convert string to float (I think b/c of multiple data types in column...)
July 17, 2022 -

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.

🌐
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 - 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: ‘Male’ as per image below. Would someone ...
🌐
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 - You can solve this error by adding a handler that makes sure your code does not continue running if the user inserts an invalid value. Alternatively, you can add in additional input validation before converting a number to a float() to make ...
Find elsewhere
🌐
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.
🌐
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 - #attempt to convert 'revenue' from string to float df['revenue'] = df['revenue'].astype(float) ValueError: could not convert string to float: '$400.42'
🌐
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)
🌐
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 Valueerror: could not convert string to float will be raised if we try to convert an incorrect string to a float. Only particular string values can be converted to floats in Python.
🌐
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. In this article, we will discuss a few approaches to handling it using some examples. When the string in the dataframe contains inappropriate characters that cause problems in converting the string to a float type, the replace() method is a good and easy way to remove those characters from the string...
🌐
AskPython
askpython.com › home › resolving python’s valueerror: cannot convert string to float
Resolving Python's ValueError: Cannot Convert String to Float - AskPython
May 25, 2023 - Since it’s impractical to convert a string or any other data type other than an integer into a float type, the Python interpreter raises an exception. This error is demonstrated below: ValueError Traceback (most recent call last) <ipython-input-1-3038d8149efd> in <cell line: 2>() ValueError: could not ...
🌐
Python Guides
pythonguides.com › could-not-convert-string-to-float-python
Could Not Convert String To Float In Python
April 18, 2024 - In the solution, we use the replace() method to replace the “$” sign with the empty string, so now only the numeric part is left. If the string contains only the numeric part, it can be converted to a float in Python using the float() method.
🌐
Reddit
reddit.com › r/learnpython › exception has occurred: valueerror could not convert string to float: '\n' python code
r/learnpython on Reddit: Exception has occurred: ValueError could not convert string to float: '\n' python code
May 27, 2022 -

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

🌐
PyiHub
pyihub.org › home › valueerror could not convert string to float solved
ValueError Could Not Convert String to Float Solved
April 3, 2024 - ValueError could not convert string to float when we tried to convert a string into float. In Python, a string can be converted into a float value only if the string has numeric values
🌐
Medium
kasata.medium.com › debugging-the-valueerror-could-not-convert-string-to-float-in-python-e5120146615c
Debugging the ‘ValueError: could not convert string to float:’ in Python
March 24, 2024 - >>> num ='123abc' >>> num_as_float = float(num) Traceback (most recent call last): File "", line 1, in ValueError: could not convert string to float: '123abc' As you can see, since ‘123abc’ cannot be converted into a float, Python raises a ValueError.