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. This function also provides the capability to convert any suitable existing column to categorical ...
🌐
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.

🌐
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):
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.to_string.html
pandas.DataFrame.to_string — pandas 3.0.1 documentation
Formatter function to apply to columns’ elements if they are floats. This function must return a unicode string and will be applied only to the non-NaN elements, with NaN being handled by na_rep.
🌐
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 - To convert specific columns, select them and apply astype(str) only to those columns. Using apply() with a lambda function allows custom string formatting for float conversion in specific columns.
🌐
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...
Find elsewhere
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.convert_dtypes.html
pandas.DataFrame.convert_dtypes — pandas 3.0.1 documentation
Then, if possible, convert to StringDtype, BooleanDtype or an appropriate integer or floating extension type, otherwise leave as object. If the dtype is integer, convert to an appropriate integer extension type. If the dtype is numeric, and consists of all integers, convert to an appropriate integer extension type. Otherwise, convert to an appropriate floating extension type.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-strings-to-floats-in-pandas-dataframe
How to Convert String to Float in Pandas DataFrame - GeeksforGeeks
January 18, 2024 - In this post, we'll see different ways to Convert Floats to Strings in Pandas Dataframe? Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to String, String to Integer, Float to String, etc.
🌐
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.

🌐
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 - Use pd.to_numeric() to convert a column to numeric type. Use astype(float) for straightforward conversion if data is clean. Handle string formatting issues like commas or currency symbols beforehand.
🌐
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.
🌐
Delft Stack
delftstack.com › home › howto › python › python float to string
How to Convert Float to String in Python | Delft Stack
February 25, 2025 - They are particularly useful in ... we explored three effective methods to convert a float to a string in Python: using the str() function, the format() method, and f-strings....
🌐
Iditect
iditect.com › program-example › python--pandas-dataframe-interpreting-columns-as-float-instead-of-string.html
python - Pandas Dataframe interpreting columns as float instead of String
Description: This query addresses the issue of a specific column being interpreted as float instead of string in a Pandas DataFrame. # Convert specific column to string type df['column_name'] = df['column_name'].astype(str)
🌐
Practical Business Python
pbpython.com › currency-cleanup.html
Cleaning Up Currency Data with Pandas - Practical Business Python
Since all values are stored as strings, the replacement code works as expected and does not incorrectly convert some values to NaN. The pandas object data type is commonly used to store strings. However, you can not assume that the data types in a column of pandas objects will all be strings. This can be especially confusing when loading messy currency data that might include numeric values with symbols as well as integers and floats.
🌐
Statistics Globe
statisticsglobe.com › home › python programming language for statistics & data science › convert string to float in pandas dataframe column in python (4 examples)
Convert String to Float in pandas DataFrame Column in Python (Example)
May 2, 2022 - This example shows how to convert only one specific variable in a pandas DataFrame to the float data class. For this task, we can use the astype function as shown in the following Python code:
🌐
Cherry Servers
cherryservers.com › home › blog › python › how to convert string to float in python (6 different ways)
How to Convert String to Float in Python (6 Different Ways) | Cherry Servers
July 25, 2024 - ... Using the float() function is the most common way to convert string to float in Python. What’s more, it is a built-in function which means it comes with standard Python installation.
🌐
datagy
datagy.io › home › pandas tutorials › data analysis in pandas › converting pandas dataframe column from object to float
Converting Pandas DataFrame Column from Object to Float • datagy
May 7, 2023 - While one column looks like a float, it’s actually formatted as a string. We can confirm this by checking the datatypes of the DataFrame: # Check the Data Types print(df.dtypes) # Returns: # Quantity int64 # Price object # dtype: object · We can see that the Price column’s data type is actually an object. Let’s now dive into how we can convert the column to a floating point value.