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.
Discussions

Could not convert string to float
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? More on discuss.python.org
🌐 discuss.python.org
0
0
January 6, 2022
Python pandas - can't convert string to float (I think b/c of multiple data types in column...)
Thanks u/Ihaveamodel3 for the solution, the original post was 95% of the way there. I added coerce & now it seems to work... dfteam1["cloff"] = pd.to_numeric(dfteam1["cloff"],errors='coerce') funny how coerce was needed. Thanks to u/omgu8mynewt for your reply as well. More on reddit.com
🌐 r/learnpython
5
1
July 17, 2022
How Do I Convert String To Float?
I had to answer this, because I could find no answer anywhere. I tried Parse and TryParse. I wrote my string to the Debug Log and saw that the string contained only a number. So, I tried the Try Catch and found the following error: · Here is my solution: OKtoFire = true; string angle1 = ... More on discussions.unity.com
🌐 discussions.unity.com
1
0
August 16, 2022
Value error in Python: Could not convert string to float: Male
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 ... More on discuss.python.org
🌐 discuss.python.org
0
0
January 24, 2024
🌐
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: ... ...
🌐
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)
🌐
Medium
kasata.medium.com › debugging-python-errors-valueerror-could-not-convert-string-to-float-4f37f891d397
Debugging Python Errors: ValueError: could not convert string to float: | by KASATA - TechVoyager | Medium
August 2, 2024 - value = "123.45a" try: float_value = float(value) except ValueError: print(f"Cannot convert '{value}' to float.") This approach ensures that your program continues running even if an error occurs, and it can provide helpful error messages for troubleshooting. In conclusion, the ValueError: could not convert string to float: can be a common stumbling block when working with user input or data parsing in Python.
Find elsewhere
🌐
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?
🌐
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.

🌐
Unity
discussions.unity.com › unity engine
How Do I Convert String To Float? - Unity Engine - Unity Discussions
August 16, 2022 - I wrote my string to the Debug Log and saw that the string contained only a number. So, I tried the Try Catch and found the following error: · Here is my solution: OKtoFire = true; string angle1 = ...
🌐
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 ...
🌐
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(“.”, “”,...
Top answer
1 of 2
1

The following would be useful,

print (heterozygosity_df.columns)

This looks like static typing issue within pandas. What I suspect is heterozygosity_df.['chrI'] is a column in the dataframe. What I think has happened is there's a mix of strings and floats within this column. pandas has set this as a "string" but you are wanting to perform numerical operations. Thus the solution is simply

print(heterozygosity_df.dtypes) # this should state 'chrI' is a "category" or "string"
heterozygosity_df['chrI'] = heterozygosity_df['chrI'].astype(float)
print(heterozygosity_df.dtypes)

If you have multiple changes the syntax is

heterozygosity_df = heterozygosity_df.astype({'chrI':'float', 'egColumn':'category'})

I suspect there will be other errors, e.g. the header is the first row of the data column. This is because again for pandas to automatically assign a column to a "string" means there must be a string value within the column.


From the comments. I see whats happening. The easy solution is ...

replacement = {
    "chrI": 1,
    "chrII": 2,
    "chrIII": 3,
    "chrIV": 4,
    ....
}

heterozygosity_df['chr'] = heterozygosity_df['chr'].str.replace(replacement, regex=True)

From the comments ... good it works ... this is what I would have personally done ..

replacement = {
    "chrI": 1,
    "chrII": 2,
    "chrIII": 3,
    "chrIV": 4, # continue for all chromosomes
}

heterozygosity_df = pd.read_csv("file.tsv", sep="\t", header=None).set_axis(['chr', 'pos', 'het'], axis=1, copy=False)
heterozygosity_df['chr'] = heterozygosity_df['chr'].str.replace(replacement, regex=True).astype('int')

Normally str should be in place because when 'chr' is imported its an object. However, if it works thats the only thing that counts.

2 of 2
2

Ah! I finally got it to work! I used your command but I had to change it up a little bit to work with my data. The final command I used is this:

replacement = {
    "chrI": 1,
    "chrII": 2,
    "chrIII": 3,
    "chrIV": 4,
    "chrV": 5,
    "chrVI": 6,
    "chrVII": 7,
    "chrVIII": 8,
    "chrIX": 9,
    "chrX": 10,
    "chrXI": 11,
    "chrXII": 12,
    "chrXIII": 13,
    "chrXIV": 14,
    "chrXV": 15,
    "chrXVI": 16,
    "chrmt": 17
}

heterozygosity_df['chr'] = heterozygosity_df['chr'].replace(replacement, regex=False)

And with that I was able to generate plots showing all of the chromosomes! (I have to figure out how to change the axis labels from 1,2,3,4...10 back to the chromosome but that's a future problem). Thank you so much for all your help!!

🌐
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 - The way to resolve this error is to use the replace() function to replace the dollar signs in the revenue column with nothing before performing the conversion: #convert revenue column to float df['revenue'] = df['revenue'].apply(lambda x: ...
🌐
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.
🌐
Team Treehouse
teamtreehouse.com › community › could-not-convert-string-to-float-e
(could not convert string to float: 'e') (Example) | Treehouse Community
May 21, 2018 - Catch here is: Strings are only converted to floating point number if you try to convert numbers represented as string. Note: float('This is number 3') will not be converted because its a combination of letters and numbers strings and Python ...
🌐
Arduino Forum
forum.arduino.cc › forum 2005-2010 (read only) › software › syntax & programs
How To Convert String to Float - Syntax & Programs - Arduino Forum
November 28, 2010 - I have a situation where I receive via a serial port a "floating point number". I convert the incoming serial stream into a String value. Now I need to convert the String to a floating point number for use by the Arduino code. I found this sample code on the forum: char* strVal = "3.1415"; float fVal = atop(strVal); my problem is that although the sample compiles cleanly, if I change the first line to be: char* strVal = IncomingStringValfromSerial; I get the following compiler error: can...
🌐
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...
🌐
ONEXT DIGITAL
onextdigital.com › home › valueerror: could not convert string to float: easy ways to fix it in python
Valueerror: could not convert string to float: Easy ways to fix it in Python
April 12, 2023 - Reason: A valid number, such as an integer or text, can be converted into a floating-point number using the float() method provided by Python. ... try: float_value = float(string_value) except ValueError: print("Error: could not convert string to float")
🌐
Rust Programming Language
users.rust-lang.org › help
Convert a string which contains either integer or float to float - help - The Rust Programming Language Forum
May 13, 2020 - Hi, I am reading lines of text file which contains Integers and Float in one column. Some thing like below. 1234 5678.9 When I read this line by line and do .parse:: ().unwrap(), I am getting a panic, Err value: ParseFloatError { kind: Invalid } I know I can solve this with if and else condition ...