Convert Data Type of pandas DataFrame Column in Python (Example Code)
In this tutorial, I’ll show how to change the column type of a pandas DataFrame in Python programming.
Setting up the Example
import pandas as pd # Import pandas library in Python |
import pandas as pd # Import pandas library in Python
my_df = pd.DataFrame({"A":["1.5", "7.1", "3.33", "5.5"], "B":range(1, 5)}) print(my_df) # Print example data # A B # 0 1.5 1 # 1 7.1 2 # 2 3.33 3 # 3 5.5 4 |
my_df = pd.DataFrame({"A":["1.5", "7.1", "3.33", "5.5"], "B":range(1, 5)}) print(my_df) # Print example data # A B # 0 1.5 1 # 1 7.1 2 # 2 3.33 3 # 3 5.5 4
Example: Convert pandas DataFrame Column from Character String to Float
my_df["A"] = my_df["A"].astype(float) # Convert variable type to float |
my_df["A"] = my_df["A"].astype(float) # Convert variable type to float
print(my_df.dtypes) # Print data types of all columns # A float64 # B int64 # dtype: object |
print(my_df.dtypes) # Print data types of all columns # A float64 # B int64 # dtype: object