Convert String Column to Float Data Type in pandas DataFrame in Python (3 Examples)
This tutorial demonstrates how to change a string column to the float data type in a pandas DataFrame in the Python programming language.
Creation of Example Data
import pandas as pd # Import pandas |
import pandas as pd # Import pandas
df = pd.DataFrame({'A':['15', '2', '12', '9', '7'], # Constructing a pandas DataFrame 'B':['10', '21', '4', '15', '25'], 'C':['35', '4', '51', '77', '8']}) print(df) # A B C # 0 15 10 35 # 1 2 21 4 # 2 12 4 51 # 3 9 15 77 # 4 7 25 8 |
df = pd.DataFrame({'A':['15', '2', '12', '9', '7'], # Constructing a pandas DataFrame 'B':['10', '21', '4', '15', '25'], 'C':['35', '4', '51', '77', '8']}) print(df) # A B C # 0 15 10 35 # 1 2 21 4 # 2 12 4 51 # 3 9 15 77 # 4 7 25 8
print(df.dtypes) # Printing the data types of all columns # A object # B object # C object # dtype: object |
print(df.dtypes) # Printing the data types of all columns # A object # B object # C object # dtype: object
Example 1: Transforming One Column of a pandas DataFrame from String to Float
df1 = df.copy() # Duplicate pandas DataFrame df1['A'] = df1['A'].astype(float) # Converting string to float |
df1 = df.copy() # Duplicate pandas DataFrame df1['A'] = df1['A'].astype(float) # Converting string to float
print(df1.dtypes) # Printing the data types of all columns # A float64 # B object # C object # dtype: object |
print(df1.dtypes) # Printing the data types of all columns # A float64 # B object # C object # dtype: object
Example 2: Transforming Multiple Columns of a pandas DataFrame from String to Float
df2 = df.copy() # Duplicate pandas DataFrame df2 = df2.astype({'A': float, 'C': float}) # Converting string to float |
df2 = df.copy() # Duplicate pandas DataFrame df2 = df2.astype({'A': float, 'C': float}) # Converting string to float
print(df2.dtypes) # Printing the data types of all columns # A float64 # B object # C float64 # dtype: object |
print(df2.dtypes) # Printing the data types of all columns # A float64 # B object # C float64 # dtype: object
Example 3: Transforming Each Column of a pandas DataFrame from String to Float
df3 = df.copy() # Duplicate pandas DataFrame df3 = df3.astype(float) # Converting string to float |
df3 = df.copy() # Duplicate pandas DataFrame df3 = df3.astype(float) # Converting string 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
Further Resources & Related Articles
You may find some related Python tutorials on topics such as groups and counting below: