You can use select_dtypes to find the column names:

s = df.select_dtypes(include='object').columns
df[s] = df[s].astype("float")
Answer from Henry Yik on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ pandas โ€บ convert-pandas-dataframe-column-to-float
Convert Pandas Dataframe Column To Float - GeeksforGeeks
July 23, 2025 - As you observe the output the data type of the string column is changed from object to float after using to_numeric() function. We can handle Non-convertible values, Missing values, and NaN values by using errors='coerce' parameter in ...
๐ŸŒ
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 - # Convert multiple columns df = ... Type of the columns: # Fee float64 # Discount float64 # dtype: object ยท By default astype() function converts all columns to the same type....
Discussions

Pandas dataframe columns won't convert to float
could you try this , dp03_cleaned[columns] = dp03_cleaned[columns].apply(pd.to_numeric, errors='coerce') More on reddit.com
๐ŸŒ r/learnpython
9
0
May 14, 2022
python - Change column type in pandas - Stack Overflow
The best way to convert one or more columns of a DataFrame to numeric values is to use pandas.to_numeric(). This function will try to change non-numeric objects (such as strings) into integers or floating-point numbers as appropriate. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Converting strings to floats in a DataFrame - Stack Overflow
How to covert a DataFrame column containing strings and NaN values to floats. And there is another column whose values are strings and floats; how to convert this entire column to floats. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - pandas how to convert all the string value to float - Stack Overflow
I want to convert all the string value in Pandas DataFrame into float, and I can define a short function to do this, but it's not a Pythonic way to do that. My DataFrame looks like this: >>&... More on stackoverflow.com
๐ŸŒ stackoverflow.com
People also ask

How do I convert an object column to float in pandas?
Object columns can be converted to float using pd.to_numeric() or astype(float). Example: df['column'] = pd.to_numeric(df['column']). This safely converts string values to numeric format.
๐ŸŒ
golinuxcloud.com
golinuxcloud.com โ€บ home โ€บ python pandas โ€บ convert pandas dataframe column to float (astype, to_numeric & practical examples)
Convert pandas DataFrame Column to Float (astype, to_numeric & ...
What is the difference between astype() and to_numeric() in pandas?
astype() directly converts the data type but fails if invalid values exist. pd.to_numeric() is more flexible and can handle errors using parameters like errors='coerce'.
๐ŸŒ
golinuxcloud.com
golinuxcloud.com โ€บ home โ€บ python pandas โ€บ convert pandas dataframe column to float (astype, to_numeric & practical examples)
Convert pandas DataFrame Column to Float (astype, to_numeric & ...
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.astype.html
pandas.DataFrame.astype โ€” pandas 3.0.1 documentation
This method allows the conversion of the data types of pandas objects, including DataFrames and Series, to the specified dtype. It supports casting entire objects to a single data type or applying different data types to individual columns using a mapping.
๐ŸŒ
Skytowner
skytowner.com โ€บ explore โ€บ converting_column_type_to_float_in_pandas_dataframe
Converting column type to float in Pandas DataFrame
To convert the column type to float in Pandas DataFrame, either use the Series' astype() method, or use Pandas' to_numeric() method.
Find elsewhere
๐ŸŒ
Saturn Cloud
saturncloud.io โ€บ blog โ€บ how-to-convert-a-column-in-pandas-dataframe-from-string-to-float
How to Convert a Column in Pandas DataFrame from String to Float | Saturn Cloud Blog
October 27, 2023 - Converting a column in a pandas DataFrame from a string to a float is a simple task that can be accomplished using the astype() method. In this blog post, we covered the steps required to convert a column from a string to a float.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ pandas dataframe columns won't convert to float
r/learnpython on Reddit: Pandas dataframe columns won't convert to float
May 14, 2022 -

I'm creating a pandas dataframe using US census data for a project I'm working on, and I'm having a problem converting the datatype of my columns to a numeric value. I've tried a couple different ways and keep running into the same issue.

dp03_emp = pd.read_csv('DP03_employment.csv',header=1).iloc[1:, :]

dp03_cleaned = dp03_emp[['Percent!!EMPLOYMENT STATUS!!Percent Unemployed',
                        'Estimate!!INCOME AND BENEFITS (IN 2011 INFLATION-ADJUSTED DOLLARS)!!Median household income (dollars)',
                        'Estimate!!INCOME AND BENEFITS (IN 2011 INFLATION-ADJUSTED DOLLARS)!!Mean household income (dollars)',
                        'Percent!!PERCENTAGE OF FAMILIES AND PEOPLE WHOSE INCOME IN THE PAST 12 MONTHS IS BELOW THE POVERTY LEVEL!!All people',
                        'Geographic Area Name',
                        'Survey Year']]

columns = ['Percent Unemployed','Median Household Income','Mean Household Income', 'Percent below poverty line']
dp03_cleaned[columns]=pd.to_numeric(columns,errors='coerce')

I know that using the 'coerce' argument will assign everything that is not recognized as a number either null or NaN, which is what happens to every value.

dp03_cleaned.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 20110 entries, 1 to 20110
Data columns (total 6 columns):
 #   Column                      Non-Null Count  Dtype  
---  ------                      --------------  -----  
 0   Percent Unemployed          0 non-null      float64
 1   Median Household Income     0 non-null      float64
 2   Mean Household Income       0 non-null      float64
 3   Percent below poverty line  0 non-null      float64
 4   Geographic Area Name        20109 non-null  object 
 5   Survey Year                 20109 non-null  float64
dtypes: float64(5), object(1)
memory usage: 942.8+ KB

I've also tried changing the datatype at the point of import in the read_csv dtype option, but it gives an error as well.

Sorry if this is a simple question, I've spent a fair bit of time trying to Google it and haven't had any luck. Thanks in advance for the help.

๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ change a column type in a dataframe in python pandas
Change a column type in a DataFrame in Python Pandas | Sentry
If we want to convert a column to a sensible numeric data type (integer or float), we should use the to_numeric function. If we want Pandas to decide which data types to use for each column, we should use the convert_dtypes method.
๐ŸŒ
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 - Similar to the example above, you can use the Pandas astype method to convert all columns from strings to floats. This can be done by applying the method to the DataFrame as a whole.
Top answer
1 of 16
2632

You have four main options for converting types in pandas:

  1. to_numeric() - provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See also to_datetime() and to_timedelta().)

  2. astype() - convert (almost) any type to (almost) any other type (even if it's not necessarily sensible to do so). Also allows you to convert to categorial types (very useful).

  3. infer_objects() - a utility method to convert object columns holding Python objects to a pandas type if possible.

  4. convert_dtypes() - convert DataFrame columns to the "best possible" dtype that supports pd.NA (pandas' object to indicate a missing value).

Read on for more detailed explanations and usage of each of these methods.


1. to_numeric()

The best way to convert one or more columns of a DataFrame to numeric values is to use pandas.to_numeric().

This function will try to change non-numeric objects (such as strings) into integers or floating-point numbers as appropriate.

Basic usage

The input to to_numeric() is a Series or a single column of a DataFrame.

>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0      8
1      6
2    7.5
3      3
4    0.9
dtype: object

>>> pd.to_numeric(s) # convert everything to float values
0    8.0
1    6.0
2    7.5
3    3.0
4    0.9
dtype: float64

As you can see, a new Series is returned. Remember to assign this output to a variable or column name to continue using it:

# convert Series
my_series = pd.to_numeric(my_series)

# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])

You can also use it to convert multiple columns of a DataFrame via the apply() method:

# convert all columns of DataFrame
df = df.apply(pd.to_numeric) # convert all columns of DataFrame

# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)

As long as your values can all be converted, that's probably all you need.

Error handling

But what if some values can't be converted to a numeric type?

to_numeric() also takes an errors keyword argument that allows you to force non-numeric values to be NaN, or simply ignore columns containing these values.

Here's an example using a Series of strings s which has the object dtype:

>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0         1
1         2
2       4.7
3    pandas
4        10
dtype: object

The default behaviour is to raise if it can't convert a value. In this case, it can't cope with the string 'pandas':

>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string

Rather than fail, we might want 'pandas' to be considered a missing/bad numeric value. We can coerce invalid values to NaN as follows using the errors keyword argument:

>>> pd.to_numeric(s, errors='coerce')
0     1.0
1     2.0
2     4.7
3     NaN
4    10.0
dtype: float64

The third option for errors is just to ignore the operation if an invalid value is encountered:

>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched

This last option is particularly useful for converting your entire DataFrame, but don't know which of our columns can be converted reliably to a numeric type. In that case, just write:

df.apply(pd.to_numeric, errors='ignore')

The function will be applied to each column of the DataFrame. Columns that can be converted to a numeric type will be converted, while columns that cannot (e.g. they contain non-digit strings or dates) will be left alone.

Downcasting

By default, conversion with to_numeric() will give you either an int64 or float64 dtype (or whatever integer width is native to your platform).

That's usually what you want, but what if you wanted to save some memory and use a more compact dtype, like float32, or int8?

to_numeric() gives you the option to downcast to either 'integer', 'signed', 'unsigned', 'float'. Here's an example for a simple series s of integer type:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

Downcasting to 'integer' uses the smallest possible integer that can hold the values:

>>> pd.to_numeric(s, downcast='integer')
0    1
1    2
2   -7
dtype: int8

Downcasting to 'float' similarly picks a smaller than normal floating type:

>>> pd.to_numeric(s, downcast='float')
0    1.0
1    2.0
2   -7.0
dtype: float32

2. astype()

The astype() method enables you to be explicit about the dtype you want your DataFrame or Series to have. It's very versatile in that you can try and go from one type to any other.

Basic usage

Just pick a type: you can use a NumPy dtype (e.g. np.int16), some Python types (e.g. bool), or pandas-specific types (like the categorical dtype).

Call the method on the object you want to convert and astype() will try and convert it for you:

# convert all DataFrame columns to the int64 dtype
df = df.astype(int)

# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})

# convert Series to float16 type
s = s.astype(np.float16)

# convert Series to Python strings
s = s.astype(str)

# convert Series to categorical type - see docs for more details
s = s.astype('category')

Notice I said "try" - if astype() does not know how to convert a value in the Series or DataFrame, it will raise an error. For example, if you have a NaN or inf value you'll get an error trying to convert it to an integer.

As of pandas 0.20.0, this error can be suppressed by passing errors='ignore'. Your original object will be returned untouched.

Be careful

astype() is powerful, but it will sometimes convert values "incorrectly". For example:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

These are small integers, so how about converting to an unsigned 8-bit type to save memory?

>>> s.astype(np.uint8)
0      1
1      2
2    249
dtype: uint8

The conversion worked, but the -7 was wrapped round to become 249 (i.e. 28 - 7)!

Trying to downcast using pd.to_numeric(s, downcast='unsigned') instead could help prevent this error.


3. infer_objects()

Version 0.21.0 of pandas introduced the method infer_objects() for converting columns of a DataFrame that have an object datatype to a more specific type (soft conversions).

For example, here's a DataFrame with two columns of object type. One holds actual integers and the other holds strings representing integers:

>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a    object
b    object
dtype: object

Using infer_objects(), you can change the type of column 'a' to int64:

>>> df = df.infer_objects()
>>> df.dtypes
a     int64
b    object
dtype: object

Column 'b' has been left alone since its values were strings, not integers. If you wanted to force both columns to an integer type, you could use df.astype(int) instead.


4. convert_dtypes()

Version 1.0 and above includes a method convert_dtypes() to convert Series and DataFrame columns to the best possible dtype that supports the pd.NA missing value.

Here "best possible" means the type most suited to hold the values. For example, this a pandas integer type, if all of the values are integers (or missing values): an object column of Python integer objects are converted to Int64, a column of NumPy int32 values, will become the pandas dtype Int32.

With our object DataFrame df, we get the following result:

>>> df.convert_dtypes().dtypes                                             
a     Int64
b    string
dtype: object

Since column 'a' held integer values, it was converted to the Int64 type (which is capable of holding missing values, unlike int64).

Column 'b' contained string objects, so was changed to pandas' string dtype.

By default, this method will infer the type from object values in each column. We can change this by passing infer_objects=False:

>>> df.convert_dtypes(infer_objects=False).dtypes                          
a    object
b    string
dtype: object

Now column 'a' remained an object column: pandas knows it can be described as an 'integer' column (internally it ran infer_dtype) but didn't infer exactly what dtype of integer it should have so did not convert it. Column 'b' was again converted to 'string' dtype as it was recognised as holding 'string' values.

2 of 16
552

Use this:

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df

Out[16]:
  one  two three
0   a  1.2   4.2
1   b   70  0.03
2   x    5     0

df.dtypes

Out[17]:
one      object
two      object
three    object

df[['two', 'three']] = df[['two', 'three']].astype(float)

df.dtypes

Out[19]:
one       object
two      float64
three    float64
๐ŸŒ
Java2Blog
java2blog.com โ€บ home โ€บ python โ€บ pandas โ€บ pandas convert column to float
Pandas convert column to float - Java2Blog
May 26, 2020 - You can use asType(float) to convert string to float in Pandas. Here is the syntax: Here is an example. We will convert data type of Column Rating from object to float64 Sample Employee data for this Example.
๐ŸŒ
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 - Example: In this example, we'll convert each value of the 'Inflation Rate' column to float. ... # importing pandas library import pandas as pd # creating a dictionary Data = {'Year': ['2016', '2017', '2018', '2019'], 'Inflation Rate': ['4.47', '5', '5.98', '4.1']} # create a dataframe df = pd.DataFrame(Data) # converting each value of column to a string df['Inflation Rate'] = pd.to_numeric(df['Inflation Rate']) # show the dataframe print(df) # show the data types print (df.dtypes)
๐ŸŒ
Statology
statology.org โ€บ home โ€บ how to convert strings to float in pandas
How to Convert Strings to Float in Pandas
November 28, 2022 - #convert all columns to float df = df.astype(float) #view column data types df.dtypes points float64 assists float64 rebounds float64 dtype: object
๐ŸŒ
Medium
medium.com โ€บ @tubelwj โ€บ efficient-method-to-batch-datatype-convert-from-object-to-float-in-pandas-73d381d028e1
Efficient Method to Batch Datatype Convert from object to float in Pandas | by Gen. Devin DL. | Medium
January 13, 2025 - To batch convert columns of object type to float type, we can use the pd.to_numeric() function. This function attempts to convert data into numeric types and allows us to handle values that cannot be converted.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.convert_dtypes.html
pandas.DataFrame.convert_dtypes โ€” pandas 3.0.1 documentation
DataFrame.convert_dtypes(infer_objects=True, convert_string=True, convert_integer=True, convert_boolean=True, convert_floating=True, dtype_backend='numpy_nullable')[source]# Convert columns from numpy dtypes to the best dtypes that support pd.NA.
Top answer
1 of 2
12

Assuming all values can be correctly converted to float, you can use DataFrame.astype() function to convert the type of complete dataframe to float. Example -

df = df.astype(float)

Demo -

In [5]: df = pd.DataFrame(np.array([['1', '2', '3'], ['4', '5', '6']]))

In [6]: df.astype(float)
Out[6]:
   0  1  2
0  1  2  3
1  4  5  6

In [7]: df = df.astype(float)

In [8]: df.dtypes
Out[8]:
0    float64
1    float64
2    float64
dtype: object

.astype() function also has a raise_on_error argument (which defaults to True) which you can set to False to make it ignore errors . In such cases, the original value is used in the DataFrame -

In [10]: df = pd.DataFrame([['1', '2', '3'], ['4', '5', '6'],['blah','bloh','bleh']])

In [11]: df.astype(float,raise_on_error=False)
Out[11]:
      0     1     2
0     1     2     3
1     4     5     6
2  blah  bloh  bleh

To convert just a series/column to float, again assuming all values can be converted, you can use [Series.astype()][2] . Example -

df['somecol'] = df['somecol'].astype(<type>)
2 of 2
6

Another option is to use df.convert_objects(numeric=True). It attempts to convert numeric strings to numbers, with unconvertible values becoming NaN:

import pandas as pd

df = pd.DataFrame([['1', '2', '3'], ['4', '5', 'foo'], ['bar', 'baz', 'quux']])
df = df.convert_objects(convert_numeric=True)
print(df)

yields

    0   1   2
0   1   2   3
1   4   5 NaN
2 NaN NaN NaN

In contrast, df.astype(float) would raise ValueError: could not convert string to float: quux since in the above DataFrame some strings (such as 'quux') is not numeric.

Note: in future versions of pandas (after 0.16.2) the function argument will be numeric=True instead of convert_numeric=True.

๐ŸŒ
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:
๐ŸŒ
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 time, we have set the variables x2 and x3 to the float data type. The column x1 is still a string. The following syntax shows how to switch the data type of all pandas DataFrame columns from string to float.