You can convert most of the columns by just calling convert_objects:

In [36]:

df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[36]:
Date         object
WD            int64
Manpower    float64
2nd          object
CTR          object
2ndU        float64
T1            int64
T2          int64
T3           int64
T4        float64
dtype: object

For column '2nd' and 'CTR' we can call the vectorised str methods to replace the thousands separator and remove the '%' sign and then astype to convert:

In [39]:

df['2nd'] = df['2nd'].str.replace(',','').astype(int)
df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
df.dtypes
Out[39]:
Date         object
WD            int64
Manpower    float64
2nd           int32
CTR         float64
2ndU        float64
T1            int64
T2            int64
T3            int64
T4           object
dtype: object
In [40]:

df.head()
Out[40]:
        Date  WD  Manpower   2nd   CTR  2ndU   T1    T2   T3     T4
0   2013/4/6   6       NaN  2645  5.27  0.29  407   533  454    368
1   2013/4/7   7       NaN  2118  5.89  0.31  257   659  583    369
2  2013/4/13   6       NaN  2470  5.38  0.29  354   531  473    383
3  2013/4/14   7       NaN  2033  6.77  0.37  396   748  681    458
4  2013/4/20   6       NaN  2690  5.38  0.29  361   528  541    381

Or you can do the string handling operations above without the call to astype and then call convert_objects to convert everything in one go.

UPDATE

Since version 0.17.0 convert_objects is deprecated and there isn't a top-level function to do this so you need to do:

df.apply(lambda col:pd.to_numeric(col, errors='coerce'))

See the docs and this related question: pandas: to_numeric for multiple columns

Answer from EdChum on Stack Overflow
Top answer
1 of 7
49

You can convert most of the columns by just calling convert_objects:

In [36]:

df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[36]:
Date         object
WD            int64
Manpower    float64
2nd          object
CTR          object
2ndU        float64
T1            int64
T2          int64
T3           int64
T4        float64
dtype: object

For column '2nd' and 'CTR' we can call the vectorised str methods to replace the thousands separator and remove the '%' sign and then astype to convert:

In [39]:

df['2nd'] = df['2nd'].str.replace(',','').astype(int)
df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
df.dtypes
Out[39]:
Date         object
WD            int64
Manpower    float64
2nd           int32
CTR         float64
2ndU        float64
T1            int64
T2            int64
T3            int64
T4           object
dtype: object
In [40]:

df.head()
Out[40]:
        Date  WD  Manpower   2nd   CTR  2ndU   T1    T2   T3     T4
0   2013/4/6   6       NaN  2645  5.27  0.29  407   533  454    368
1   2013/4/7   7       NaN  2118  5.89  0.31  257   659  583    369
2  2013/4/13   6       NaN  2470  5.38  0.29  354   531  473    383
3  2013/4/14   7       NaN  2033  6.77  0.37  396   748  681    458
4  2013/4/20   6       NaN  2690  5.38  0.29  361   528  541    381

Or you can do the string handling operations above without the call to astype and then call convert_objects to convert everything in one go.

UPDATE

Since version 0.17.0 convert_objects is deprecated and there isn't a top-level function to do this so you need to do:

df.apply(lambda col:pd.to_numeric(col, errors='coerce'))

See the docs and this related question: pandas: to_numeric for multiple columns

2 of 7
41

convert_objects is deprecated.

For pandas >= 0.17.0, use pd.to_numeric

df["2nd"] = pd.to_numeric(df["2nd"])
🌐
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 12, 2023 - To convert a Pandas column’s data type from object to float you can use the to_numeric function. The function allows you to pass in a Pandas column and convert it to a numeric data type, where the data type is inferred.
Discussions

python - converting a dataframe from float64 to object using dtype - Stack Overflow
Upcoming initiatives on Stack Overflow and across the Stack Exchange network... ... 1 pandas not converting an object dtype to float64 even after error free execution of df.astype('float64') More on stackoverflow.com
🌐 stackoverflow.com
python - How to convert float64 time to datetime object - Stack Overflow
I am working on Berkeley Earth Surface Temperature data. I have a monthly NetCDF file from 1753-recent. The date axis is float64 and when I convert to DateTime format it only returns the first day ... More on stackoverflow.com
🌐 stackoverflow.com
grouby( ... , as_index=False) convert "float64" to "object" type.
There was an error while loading. Please reload this page More on github.com
🌐 github.com
3
May 15, 2013
python - Convert Float to String in Pandas - Stack Overflow
> df.dtypes Col1 float64 Col2 object dtype: object ... I believe if I convert "object" to "String", I will get to do what I want. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › how do i convert a object to a float.
r/learnpython on Reddit: How do I convert a object to a float.
April 7, 2022 -

Hi guys, im struggeling with my dataframe.

Im trying to get a percentage of 2 columns, but when I divide the 2 I get this error: unsupported operand type(s) for /: 'float' and 'str'

The dtypes of the columns are an 'object'

Im aware that I have empty data in my columns, but is that an issue?

Would appreciate your help!

🌐
Stack Overflow
stackoverflow.com › questions › 62907307 › converting-a-dataframe-from-float64-to-object-using-dtype
python - converting a dataframe from float64 to object using dtype - Stack Overflow
"df = pd.concat([pd.Series(v, name=k) for k, v in d.items()], axis=1 ) DeprecationWarning: The default dtype for empty Series will be 'object' instead of 'float64' in a future version.
🌐
Delft Stack
delftstack.com › home › howto › python pandas › pandas convert object to float
How to Convert Object to Float in Pandas | Delft Stack
February 2, 2024 - This tutorial has extensively covered converting an object-type column to float in Pandas, showcasing three distinct approaches: using the astype() method, employing the to_numeric() function, and harnessing the power of the apply() function ...
🌐
Statology
statology.org › home › how to convert object to float in pandas (with examples)
How to Convert Object to Float in Pandas (With Examples)
May 11, 2022 - Notice that the points column now has a data type of float64. The following code shows how to use the to_numeric() function to convert the points column in the DataFrame from an object to a float:
Find elsewhere
🌐
Zhihu
zhihu.com › en › answer › 2273833227
In Pandas, how do you convert an object to a float type?
Can you accept that your future child will take the mother's surname · Actually, I still support it. If it's a two-way marriage, the economic burden on families with sons would be reduced by more than a little.Actually, I still support it. If it's a two-way marriage, the economic burden on ...
🌐
GitHub
github.com › pandas-dev › pandas › issues › 3610
grouby( ... , as_index=False) convert "float64" to "object" type. · Issue #3610 · pandas-dev/pandas
May 15, 2013 - In [1]: import pandas as pd In [2]: df = pd.DataFrame({"c1" : [1,2,6,6,8]}) In [3]: df["c2"] = df.c1/2.0 In [4]: df.groupby("c2").mean().reset_index().c2 Out[4]: 0 0.5 1 1.0 2 3.0 3 4.0 Name: c2, dtype: float64 In [5]: df.groupby("c2", as_index=False).mean().c2 Out[5]: 0 0.5 1 1 2 3 3 4 Name: c2, dtype: object
Author: pandas-dev
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.

🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.to_numeric.html
pandas.to_numeric — pandas 3.0.6 documentation - PyData |
Convert dtypes. ... >>> s = pd.Series(["1.0", "2", -3]) >>> pd.to_numeric(s) 0 1.0 1 2.0 2 -3.0 dtype: float64 >>> pd.to_numeric(s, downcast="float") 0 1.0 1 2.0 2 -3.0 dtype: float32 >>> pd.to_numeric(s, downcast="signed") 0 1 1 2 2 -3 dtype: int8 >>> s = pd.Series(["apple", "1.0", "2", -3]) >>> pd.to_numeric(s, errors="coerce") 0 NaN 1 1.0 2 2.0 3 -3.0 dtype: float64
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › convert-pandas-dataframe-column-to-float
Convert Pandas Dataframe Column To Float - GeeksforGeeks
July 23, 2025 - Data types before conversion: C1 object C2 object dtype: object Data types after conversion: C1 float64 C2 float64 dtype: object DataFrame after conversion: C1 C2 0 10.5 15.3 1 20.7 25.6 2 30.2 35.8
🌐
Sentry
sentry.io › sentry answers › python › change a column type in a dataframe in python pandas
Python Change Column Dtype in Pandas With astype() | Sentry
import pandas as pd # Create and print DataFrame df = pd.DataFrame({ 'A': [1.0, 2.0, 5.3], 'B': ['z', 'x', 'c'], 'C': [7, 8, 4], 'D': ['1', '2', '3'] }) print(df) # Print data types of each column in DataFrame print("\n") print(df.dtypes) # Change all columns to the appropriate types df = df.convert_dtypes() print("\nConverted:\n") # Print altered DataFrame print(df) # Print data types of each column in DataFrame print("\n") print(df.dtypes) ... A B C D 0 1.0 z 7 1 1 2.0 x 8 2 2 5.3 c 4 3 A float64 B object C int64 D object dtype: object Converted: A B C D 0 1.0 z 7 1 1 2.0 x 8 2 2 5.3 c 4 3 A Float64 B string C Int64 D string dtype: object
🌐
HatchJS
hatchjs.com › home › how to convert float64 to object in pandas
How to Convert Float64 to Object in Pandas
January 5, 2024 - Since missing values are represented as NaN (not a number) in float64 columns, they would be ignored by mathematical operations. However, if you convert the column to an object column, the missing values will be treated as strings and included in the mathematical operation.
🌐
Python
docs.python.org › 3 › c-api › float.html
Floating-Point Objects — Python 3.15.0 documentation
This instance of PyTypeObject represents the Python floating-point type. This is the same object as float in the Python layer.
🌐
Stack Overflow
stackoverflow.com › questions › 68321520 › how-to-convert-an-array-of-numpy-float64-into-an-array-of-float64
python - How to convert an array of numpy.float64 into an array of float64? - Stack Overflow
There is ndarray.tolist() which converts the array to ordinary (nested) lists. ... I'm trying to run this specific line : self.x = torch.from_numpy(X_train)[train], but the content of my X_train contains numpy.float64 instead of regular 64, hence the issue ... @MVMV If I put that into my python, I get name X_train is not defined.
🌐
Practical Business Python
pbpython.com › pandas_dtypes.html
Overview of Pandas Data Types - Practical Business Python
An object is a string in pandas so it performs a string operation instead of a mathematical one. If we want to see what all the data types are in a dataframe, use df.dtypes ... Customer Number float64 Customer Name object 2016 object 2017 object Percent Growth object Jan Units object Month int64 Day int64 Year int64 Active object dtype: object
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-float64-columns-to-int64-in-pandas
How to Convert float64 Columns to int64 in Pandas? - GeeksforGeeks
July 11, 2024 - This enables the conversion of a column from various data types such as float or string to an integer type, specifically int64 or int32. We can use astype() method in Python to convert float64 Columns to int64 in Pandas.