Convert Integer Columnin in pandas DataFrame to Float in Python (3 Examples)
This tutorial shows how to transform an integer variable in a pandas DataFrame to the float data type in the Python programming language.
Creating Example Data
import pandas as pd # Import pandas |
import pandas as pd # Import pandas
df = pd.DataFrame({'A':[4, 9, 12, 1, 7], # Constructing a pandas DataFrame 'B':[10, 9, 77, 22, 24], 'C':[35, 41, 41, 1, 13]}) print(df) # A B C # 0 4 10 35 # 1 9 9 41 # 2 12 77 41 # 3 1 22 1 # 4 7 24 13 |
df = pd.DataFrame({'A':[4, 9, 12, 1, 7], # Constructing a pandas DataFrame 'B':[10, 9, 77, 22, 24], 'C':[35, 41, 41, 1, 13]}) print(df) # A B C # 0 4 10 35 # 1 9 9 41 # 2 12 77 41 # 3 1 22 1 # 4 7 24 13
print(df.dtypes) # Printing the data types of all columns # A int64 # B int64 # C int64 # dtype: object |
print(df.dtypes) # Printing the data types of all columns # A int64 # B int64 # C int64 # dtype: object
Example 1: Transforming One Column of a pandas DataFrame from Integer to Float
df1 = df.copy() # Duplicate pandas DataFrame df1['A'] = df1['A'].astype(float) # Converting integer to float |
df1 = df.copy() # Duplicate pandas DataFrame df1['A'] = df1['A'].astype(float) # Converting integer to float
print(df1.dtypes) # Printing the data types of all columns # A float64 # B int64 # C int64 # dtype: object |
print(df1.dtypes) # Printing the data types of all columns # A float64 # B int64 # C int64 # dtype: object
Example 2: Transforming Multiple Columns of a pandas DataFrame from Integer to Float
df2 = df.copy() # Duplicate pandas DataFrame df2 = df2.astype({'A': float, 'C': float}) # Converting integer to float |
df2 = df.copy() # Duplicate pandas DataFrame df2 = df2.astype({'A': float, 'C': float}) # Converting integer to float
print(df2.dtypes) # Printing the data types of all columns # A float64 # B int64 # C float64 # dtype: object |
print(df2.dtypes) # Printing the data types of all columns # A float64 # B int64 # C float64 # dtype: object
Example 3: Transforming Each Column of a pandas DataFrame from Integer to Float
df3 = df.copy() # Duplicate pandas DataFrame df3 = df3.astype(float) # Converting integer to float |
df3 = df.copy() # Duplicate pandas DataFrame df3 = df3.astype(float) # Converting integer to float
print(df3.dtypes) # Printing the data types of all columns # A float64 # B float64 # C float64 # dtype: object |
print(df3.dtypes) # Printing the data types of all columns # A float64 # B float64 # C float64 # dtype: object
Related Articles & Further Resources
You may find some related Python tutorials on topics such as data conversion and naming data in the following list.