How to Convert Integers to Floats in Pandas DataFrame

In this short guide, I’ll review two methods to convert integers to floats in Pandas DataFrame:

(1) The astype(float) method:

df['DataFrame Column'] = df['DataFrame Column'].astype(float)

(2) The to_numeric method:

df['DataFrame Column'] = pd.to_numeric(df['DataFrame Column'], downcast='float')

In the next section, I’ll review an example with the steps to apply the above two methods in practice.

Steps to Convert Integers to Floats in Pandas DataFrame

Step 1: Create a DataFrame

To start, create a DataFrame that contains integers.

For example, I created a simple DataFrame based on the following data (where the Price column contained the integers):

ProductPrice
AAA300
BBB500

This is the code that I used to create the DataFrame in Python:

import pandas as pd

Data = {'Product': ['AAA','BBB'],
          'Price': [300,500]}

df = pd.DataFrame(Data)
print (df)
print (df.dtypes)

Run the code, and you’ll get the following DataFrame:

Example of DataFrame

Notice that the Price column indeed contains the integers.

Step 2: Convert the Integers to Floats in Pandas DataFrame

You can apply the first method of astype(float) in order to convert the integers to floats in Pandas DataFrame:

df['DataFrame Column'] = df['DataFrame Column'].astype(float)

Since in our example the ‘DataFrame Column’ is the Price column (which contains the integers), you’ll then need to add the following syntax:

df['Price'] = df['Price'].astype(float)

So this the complete code to perform the conversion for our example:

import pandas as pd

Data = {'Product': ['AAA','BBB'],
          'Price': [300,500]}

df = pd.DataFrame(Data)
df['Price'] = df['Price'].astype(float)

print (df)
print (df.dtypes)

As you can see below, the values under the Price column are now floats:

How to Convert Integers to Floats in Pandas DataFrame

Step 3 (optional): Convert the Integers to Floats using to_numeric

For this optional step, you may use the to_numeric method to convert the integers to floats:

df['DataFrame Column'] = pd.to_numeric(df['DataFrame Column'], downcast='float')

This is the syntax that you’ll need to add in the context of our example:

df['Price'] = pd.to_numeric(df['Price'], downcast='float')

Here is the full Python code to perform the conversion from integers to floats:

import pandas as pd

Data = {'Product': ['AAA','BBB'],
          'Price': [300,500]}

df = pd.DataFrame(Data)
df['Price'] = pd.to_numeric(df['Price'], downcast='float')

print (df)
print (df.dtypes)

Run the code in Python, and you’ll get the float values:

Convert Integers to Floats in Pandas DataFrame

At times, you may need to convert strings to floats. If that’s the case, you may want to check the following guide that explains the steps to convert strings to floats in pandas DataFrame.