Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

Answer from coldspeed95 on Stack Overflow
Top answer
1 of 3
94

Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

2 of 3
20
In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]: 
0     1
1     2
2     3
3     4
4   NaN
dtype: float64
🌐
Finxter
blog.finxter.com › 5-best-ways-to-convert-pandas-series-to-float
5 Best Ways to Convert Pandas Series to Float – Be on the Right Side of Change
February 19, 2024 - This snippet shows the conversion of a pandas Series containing string representations of numbers to floats using astype(float). It’s direct and efficient but will raise an error if applied to Series with non-convertible values such as ‘a’ or ‘??’.
Discussions

TypeError: cannot convert the series to <type 'float'>
Maybe there is one value that can´t be converted. run a.dtypes to check your column´s types. If it says object, you have a mixed bag. It´s possible that there a string that wont allow the operation. Also, you can make a function to learn which value is giving you trouble. Something like this: def check_value(row): print(row['col2'], row['col3']) col1_value = round(100.0 * row['col2'] / row['col3'], 1) return col1_value a['col1'] = a.apply(check_value,axis=1) This will print the last value that was converted. More on reddit.com
🌐 r/learnpython
14
1
December 22, 2022
Convert Series to float data in python pandas - Stack Overflow
I have written code to find maximum value horizontally. Now I want to store it to other location in data frame using .iloc[] function. I am not able to do it as dtype of it is series. How to convert More on stackoverflow.com
🌐 stackoverflow.com
December 22, 2017
python - How to convert Series to class float - Stack Overflow
I am learning Python and right now I am trying to examine percent change in stock values from a database. However, one of the variables I am trying to examine is coming from a database which is of ... More on stackoverflow.com
🌐 stackoverflow.com
python - TypeError: cannot convert the series to <type 'float'> - Stack Overflow
My code is and I have some difficulties to make it run correctly. import scipy.special as sps import numpy as np import matplotlib.pyplot as plt import pandas as pd from scipy.stats import norm from More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
🌐
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
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Series.convert_dtypes.html
pandas.Series.convert_dtypes — pandas 3.0.6 documentation
By default, convert_dtypes will attempt to convert a Series (or each Series in a DataFrame) to dtypes that support pd.NA. By using the options convert_string, convert_integer, convert_boolean and convert_floating, it is possible to turn off individual conversions to StringDtype, the integer extension types, BooleanDtype or floating extension types, respectively.
🌐
Stack Overflow
stackoverflow.com › questions › 47942270 › convert-series-to-float-data-in-python-pandas
Convert Series to float data in python pandas - Stack Overflow
December 22, 2017 - If you don't want b converted to float, don't use downcast='integer'. ... That's incorrect. The slice's size must be the same as b. ... By finding maximum value using a = master.iloc[:, 154:181].max(axis=1), gives series dtype.
🌐
Stack Overflow
stackoverflow.com › questions › 54776823 › how-to-convert-series-to-class-float
python - How to convert Series to class float - Stack Overflow
I am learning Python and right now I am trying to examine percent change in stock values from a database. However, one of the variables I am trying to examine is coming from a database which is of type Series. And whenever I try to convert into a float to use it for multiplication and division, I receive an error "TypeError: cannot convert the series to ".
Find elsewhere
🌐
Pandas
pandas.pydata.org › pandas-docs › stable › reference › api › pandas.to_numeric.html
pandas.to_numeric — pandas 3.0.2 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
🌐
Delft Stack
delftstack.com › home › howto › python › python typeerror cannot convert the series to class float
How to Fix TypeError: Cannot Convert the Series to <Class 'Float'> in Python | Delft Stack
February 2, 2024 - Suppose we want to convert the spirit_servings column to a floating point rather than an integer. All we have to do is use the series method astype() and pass it float, which means we convert it to the floating-point type.
🌐
Itsourcecode
itsourcecode.com › home › typeerror cannot convert the series to class float
Fix Cannot Convert the Series to Class float() (2026 Python)
July 12, 2026 - Pandas Series object to a float data type. In simpler terms, the error message means that there is an issue with the data being used in a mathematical operation or conversion that requires numeric values. Here is an example code snippet that triggers the TypeError ... import pandas as pd # create a Pandas Series with mixed data types my_series = pd.Series([1, 2.0, "three", 4.5]) # try to convert the Series to a float data type my_series.astype(float)
🌐
Source Code Tester
sourcecodester.com › article › 16852 › python-error-typeerror-cannot-convert-series-class-float-solved.html
Python Error TypeError: cannot convert the series to class 'float' [Solved] | SourceCodester
September 22, 2023 - This error typically arises when non-numeric data is mixed with the series object or when we try to convert a pandas Series or DataFrame object's numbers into floats using Python's built-in function or method, known as float().
🌐
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 - Syntax: Series.astype(dtype, copy=True, errors=’raise’) Parameters: This method will take following parameters: dtype: Data type to convert the series into. (for example str, float, int).c
🌐
iO Flood
ioflood.com › blog › convert-string-to-float-python
Convert a String to a Float in Python: 3 Easy Methods
December 11, 2023 - The Pandas library is a powerful tool for data manipulation in Python and can be used to convert strings to floats across an entire DataFrame or Series.
🌐
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 - The following code shows how to use the astype() function to convert the points column in the DataFrame from an object to a float:
🌐
Medium
medium.com › @pies052022 › typeerror-cannot-convert-the-series-to-class-float-solved-3877c1acda18
TypeError: cannot convert the series to class float [SOLVED] | by JOKEN VILLANUEVA | Medium
January 27, 2025 - For this example, because the “col1” column in the my_df DataFrame contains the string “three”, which cannot be converted to a float, an error occurs. ... Finally, this error can occur due to version compatibility issues between the Pandas library and the version of Python being used. ... import pandas as pd # create a Pandas Series with mixed data types my_series = pd.Series([1, 2.0, "three", 4.5]) # try to convert the Series to a float data type using an older version of Pandas pd.__version__ = '0.23.4' my_series.astype(float)
🌐
GeeksforGeeks
geeksforgeeks.org › python-pandas-series-astype-to-convert-data-type-of-series
Python | Pandas Series.astype() to convert Data type of series - GeeksforGeeks
October 1, 2018 - Syntax: DataFrame.astype(dtype, copy=True, errors='raise') Parameters: dtype: Data type to convert the series into. (for example str, float, int) copy: Makes a copy of dataframe/series. errors: Error raising on conversion to invalid data type. For example dict to string.
🌐
Stack Overflow
stackoverflow.com › questions › 41323659 › typeerror-cannot-convert-the-series-to-type-float
python - TypeError: cannot convert the series to <type 'float'> - Stack Overflow
May 24, 2017 - My code is and I have some difficulties to make it run correctly. import scipy.special as sps import numpy as np import matplotlib.pyplot as plt import pandas as pd from scipy.stats import norm from
🌐
Brainly
brainly.com › computers and technology › high school › why can't the series be converted to class 'float'?
[FREE] Why can't the series be converted to class 'float'? - brainly.com
November 19, 2023 - This can be done by iterating over the series or by using vectorized operations provided by pandas. For example, if you want to convert all numeric values in the series to floats, you could use the .astype(float) method provided by pandas.