Two approaches to convert integers to floats in Pandas DataFrame:
(1) The astype(float) approach:
df['DataFrame Column'] = df['DataFrame Column'].astype(float)
(2) The apply(float) approach:
df['DataFrame Column'] = df['DataFrame Column'].apply(float)
Steps to Convert Integers to Floats in Pandas DataFrame
Step 1: Create a DataFrame
To start, create a DataFrame that contains integers.
For example, let’s create a simple DataFrame based on the following data (where the Price column contains the integers):
Product | Price |
AAA | 300 |
BBB | 500 |
CCC | 700 |
DDD | 900 |
Here is the complete code to create the DataFrame in Python:
import pandas as pd data = {'Product': ['AAA', 'BBB', 'CCC', 'DDD'], 'Price': [300, 500, 700, 900] } df = pd.DataFrame(data) print(df) print(df.dtypes)
Run the code, and you’ll see that the Price column contains integers:
Product Price
0 AAA 300
1 BBB 500
2 CCC 700
3 DDD 900
Product object
Price int64
dtype: object
Note that print(df.dtypes) was added at the bottom of the code to check the data type of each column in the DataFrame.
Step 2: Convert the Integers to Floats in Pandas DataFrame
You can apply the first approach of astype(float) in order to convert the integers to floats in Pandas DataFrame:
df['DataFrame Column'] = df['DataFrame Column'].astype(float)
For our example, let’s convert the ‘Price‘ column (which currently contains the integers) to float:
df['Price'] = df['Price'].astype(float)
So this the complete code to perform the conversion is:
import pandas as pd data = {'Product': ['AAA', 'BBB', 'CCC', 'DDD'], 'Price': [300, 500, 700, 900] } df = pd.DataFrame(data) df['Price'] = df['Price'].astype(float) print(df) print(df.dtypes)
As you can see, the values under the ‘Price’ column are now floats:
Product Price
0 AAA 300.0
1 BBB 500.0
2 CCC 700.0
3 DDD 900.0
Product object
Price float64
dtype: object
Alternatively, you may use apply(float) to convert to float values:
df['DataFrame Column'] = df['DataFrame Column'].apply(float)
For our example:
df['Price'] = df['Price'].apply(float)
The complete Python code:
import pandas as pd data = {'Product': ['AAA', 'BBB', 'CCC', 'DDD'], 'Price': [300, 500, 700, 900] } df = pd.DataFrame(data) df['Price'] = df['Price'].apply(float) print(df) print(df.dtypes)
Run the code in Python, and you’ll get the float values:
Product Price
0 AAA 300.0
1 BBB 500.0
2 CCC 700.0
3 DDD 900.0
Product object
Price float64
dtype: object
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.