If a column contains string or is treated as string, it will have a dtype of object (but not necessarily true backward -- more below). Here is a simple example:

import pandas as pd
df = pd.DataFrame({'SpT': ['string1', 'string2', 'string3'],
                   'num': ['0.1', '0.2', '0.3'],
                   'strange': ['0.1', '0.2', 0.3]})
print df.dtypes
#SpT        object
#num        object
#strange    object
#dtype: object

If a column contains only strings, we can apply len on it like what you did should work fine:

print df['num'].apply(lambda x: len(x))
#0    3
#1    3
#2    3

However, a dtype of object does not means it only contains strings. For example, the column strange contains objects with mixed types -- and some str and a float. Applying the function len will raise an error similar to what you have seen:

print df['strange'].apply(lambda x: len(x))
# TypeError: object of type 'float' has no len()

Thus, the problem could be that you have not properly converted the column to string, and the column still contains mixed object types.

Continuing the above example, let us convert strange to strings and check if apply works:

df['strange'] = df['strange'].astype(str)
print df['strange'].apply(lambda x: len(x))
#0    3
#1    3
#2    3

(There is a suspicious discrepancy between df_cleaned and df_clean there in your question, is it a typo or a mistake in the code that causes the problem?)

Answer from YS-L on Stack Overflow
Top answer
1 of 2
38

If a column contains string or is treated as string, it will have a dtype of object (but not necessarily true backward -- more below). Here is a simple example:

import pandas as pd
df = pd.DataFrame({'SpT': ['string1', 'string2', 'string3'],
                   'num': ['0.1', '0.2', '0.3'],
                   'strange': ['0.1', '0.2', 0.3]})
print df.dtypes
#SpT        object
#num        object
#strange    object
#dtype: object

If a column contains only strings, we can apply len on it like what you did should work fine:

print df['num'].apply(lambda x: len(x))
#0    3
#1    3
#2    3

However, a dtype of object does not means it only contains strings. For example, the column strange contains objects with mixed types -- and some str and a float. Applying the function len will raise an error similar to what you have seen:

print df['strange'].apply(lambda x: len(x))
# TypeError: object of type 'float' has no len()

Thus, the problem could be that you have not properly converted the column to string, and the column still contains mixed object types.

Continuing the above example, let us convert strange to strings and check if apply works:

df['strange'] = df['strange'].astype(str)
print df['strange'].apply(lambda x: len(x))
#0    3
#1    3
#2    3

(There is a suspicious discrepancy between df_cleaned and df_clean there in your question, is it a typo or a mistake in the code that causes the problem?)

2 of 2
1
"Hidden" nulls

If the column dtype is object, TypeError: object of type 'float' has no len() often occurs if the column contains NaN. Check if that's the case by calling

df['Col2'].isna().any()

If it returns True, then there's NaN and you probably need to handle that.


Vectorized str. methods

If null handling is not important, you can also call vectorized str.len(), str.isdigit() etc. methods. For example, the code in the OP can be written as:

df['Col3'] = df['Col2'].str.len().ge(2) & df['Col2'].str[0].str.isalpha()

to get the desired output without errors.


'string' dtype

Since pandas 1.0, there's a new 'string' dtype where you can keep a Nullable integer dtype after casting a column into a 'string' dtype. For example, if you want to convert floats to strings without decimals, yet the column contains NaN values that you want to keep as null, you can use 'string' dtype.

df = pd.DataFrame({
    'Col1': [1.2, 3.4, 5.5, float('nan')]
})

df['Col1'] = df['Col1'].astype('string').str.split('.').str[0]

returns

0       1
1       3
2       5
3    <NA>
Name: Col1, dtype: object

where <NA> is a Nullable integer that you can drop with dropna() while df['Col1'].astype(str) casts NaNs into strings.

🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-floats-to-strings-in-pandas-dataframe
How to Convert Floats to Strings in Pandas DataFrame? - GeeksforGeeks
July 15, 2025 - There are three methods to convert Float to String: Method 1: Using DataFrame.astype(). ... This is used to cast a pandas object to a specified dtype.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-strings-to-floats-in-pandas-dataframe
How to Convert String to Float in Pandas DataFrame - GeeksforGeeks
July 15, 2025 - Sometimes, we may not have a float value represented as a string. So, pd.to_numeric() function will show an error. To remove this error, we can use errors='coerce', to convert the value at this position to be converted to NaN.
🌐
Reddit
reddit.com › r/learnpython › pandas dataframe tries to convert a string into a float, while adding it to a column
r/learnpython on Reddit: Pandas DataFrame tries to convert a string into a float, while adding it to a column
December 13, 2021 -

Hello Guys,

I have a question regarding DataFrames. I have a line of code, which looks similar to this:

import os

import pandas as pd

import numpy as np

file_paths = ('C:/Users/DR/Documents/Polymer Science/Mitarbeiterpraktika/Forschungsmodul I Elektrochemie/Wasserspaltung/Co15-FTO_calc_WS_LS.txt', 'C:/Users/DR/Documents/Polymer Science/Mitarbeiterpraktika/Forschungsmodul I Elektrochemie/Wasserspaltung/Co16-FTO_calc_WS_LS.txt')

files_infos = pd.DataFrame()

for n, file_path in enumerate(file_paths) :

file_name = os.path.basename(file_path)

file_name = file_name.split(".txt")[0]

files_infos[file_name] = [np.nan] * len(files_infos)

files_infos.at["file_path", file_name] = file_path

If I run this script I get this Error. ValueError: could not convert string to float: 'C:/Users/DR/Documents/Polymer Science/Mitarbeiterpraktika/Forschungsmodul I Elektrochemie/Wasserspaltung/Co16-FTO_calc_WS_LS.txt'

I just don´t understand, why pandas tries to convert my string into a float. I thougt mabye it has something to do with the dtype of the DataFrame, but I couldn´t really find an answer (the dtype is object). What I find really confusing about this Error is, that I did use the same approach in different projects and it didn´t occur before.

Can someone of you mabye explain to me, why this error occurs and what I have to look up to find a solution? Please dont give me a solution to my problem, since I would like to solve it by myself in order to learn it.

Thank you for your help in advance.

🌐
Reddit
reddit.com › r/learnpython › how i convert float to string in this case?
r/learnpython on Reddit: How I convert float to string in this case?
August 21, 2022 -

I tried

n1=input('First number')
n2=input('Second number')
sum = float(n1) + float(n2)
str(sum)
print('The sum of the values is: ' + sum)

My error is:

TypeError: can only concatenate str (not "float") to str

I tried googling this error and got some answers like print(f' which I didn't really understand, and some others that looked a little complicated, I am very new.

I am trying to improve my googling skills.

🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.to_string.html
pandas.DataFrame.to_string — pandas 3.0.1 documentation
DataFrame.to_string(buf=None, *, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True, justify=None, max_rows=None, max_cols=None, show_dimensions=False, decimal='.', line_width=None, min_rows=None, max_colwidth=None, encoding=None)[source]#
🌐
Statistics Globe
statisticsglobe.com › home › python programming language for statistics & data science › convert float to string in pandas dataframe column in python (4 examples)
Convert Float to String in pandas DataFrame Column in Python (Example)
April 5, 2023 - In the previous examples, we have used the astype function to convert our float columns to the string data type. However, it is also possible to use the apply function for this task. The following Python syntax shows how to use the apply function to parse the data type of the first column (similar to Example 1):
🌐
Python Examples
pythonexamples.org › python-convert-float-to-string
Convert float to string
To convert given floating-point number to a string in Python, call str() builtin function and pass the floating-point number as argument to the str() function.
Find elsewhere
🌐
Finxter
blog.finxter.com › python-convert-float-to-string
Python Convert Float to String – Be on the Right Side of Change
If you use the f'{my_float:.2f}' expression, Python converts the float to a string representation of the rounded float with n digits.
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas convert floats to strings in dataframe
Pandas Convert Floats to Strings in DataFrame - Spark By {Examples}
December 5, 2024 - You can use the applymap() function in Pandas to apply a function to every element in a DataFrame. This is particularly useful for converting all elements, such as converting all float values to strings.
🌐
Delft Stack
delftstack.com › home › howto › python › python float to string
How to Convert Float to String in Python | Delft Stack
February 25, 2025 - This tutorial provides a comprehensive guide on how to convert a float to a string in Python. Learn various methods including str(), format(), and f-strings, complete with well-commented code examples. Perfect for beginners and seasoned developers alike, this article offers step-by-step ...
🌐
Educative
educative.io › answers › how-to-convert-float-to-string-in-python
How to convert float to string in Python
In the code snippet below, observe how we can avoid the error in the previous example by type-casting float to string in Python:
🌐
Quora
quora.com › How-can-I-convert-a-float-to-a-string-in-Python
How to convert a float to a string in Python - Quora
Answer (1 of 7): # First take any variable and assign any value to it float = 1.2 # Next take another variable(result in this code) # and use python str keyword to convert float value # to str and assign that value to another variable(result in this code) result = str(float) # print the seco...
🌐
Python Pool
pythonpool.com › home › blog › python float to string conversion using 10 different methods
Python float to string Conversion Using 10 Different Methods - Python Pool
June 14, 2021 - Here we have performed another successful conversion. We can also notice that the conversion follows the list as stated above “Float -> List -> String.” Here the str method is used to convert to the string data type.
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas convert column to float in dataframe
Pandas Convert Column to Float in DataFrame - Spark By {Examples}
October 14, 2024 - If you have empty values in a string, convert the empty string ('') with np.nan before converting it to float. import pandas as pd import numpy as np technologies= ({ 'Fee' :['22000.30','25000.40','23000.20','24000.50','26000.10','21000'], 'Discount':['1000.10',np.nan,"",np.nan,'2500.20',""] }) df = pd.DataFrame(technologies) # Replace empty string ('') with np.nan df['Discount']=df.Discount.replace('',np.nan).astype(float) print("After replacing an empty string with NaN:\n", df) print("Type of the columns:\n", df.dtypes)
🌐
Quora
quora.com › How-do-you-convert-a-string-to-a-float-in-pandas
How to convert a string to a float in pandas - Quora
If your talking about a single element, and assuming your using Python, you can just do something like this: a=”yourstring” yourfloat=float(a) finally you need to update your panda series, dataframe o...
🌐
Vultr Docs
docs.vultr.com › python › third-party › pandas › DataFrame › to_string
Python Pandas DataFrame to_string() - Convert to String Form | Vultr Docs
December 30, 2024 - In the above example, converting the DataFrame to string excludes both the index and the header, resulting in a simple list of values. Customize the format of floating-point numbers using the float_format parameter.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-convert-string-to-float
How to Convert String to Float in Python: Complete Guide with Examples | DigitalOcean
July 10, 2025 - From there, we’ll tackle practical, real-world challenges like cleaning strings with currency symbols and converting international numbers that use commas as decimals. By the end, you’ll understand the best practices for handling any string-to-float conversion task. Python’s built-in float() function handles most string-to-float conversions, including integers, decimals, negative numbers, scientific notation, and strings with leading/trailing whitespace.