Convert Float Column to String Data Type in pandas DataFrame in Python (3 Examples)
This article demonstrates how to convert a float column to the string data type in a pandas DataFrame in the Python programming language.
Setting up the Examples
import pandas as pd # Load pandas library |
import pandas as pd # Load pandas library
df = pd.DataFrame({'A':[7.4, 2.9, 12, 9.1, 7], # Constructing a pandas DataFrame 'B':[10, 9, 4.77, 22, 25.4], 'C':[35, 4.1, 42.1, 7.1, 13]}) print(df) # A B C # 0 7.4 10.00 35.0 # 1 2.9 9.00 4.1 # 2 12.0 4.77 42.1 # 3 9.1 22.00 7.1 # 4 7.0 25.40 13.0 |
df = pd.DataFrame({'A':[7.4, 2.9, 12, 9.1, 7], # Constructing a pandas DataFrame 'B':[10, 9, 4.77, 22, 25.4], 'C':[35, 4.1, 42.1, 7.1, 13]}) print(df) # A B C # 0 7.4 10.00 35.0 # 1 2.9 9.00 4.1 # 2 12.0 4.77 42.1 # 3 9.1 22.00 7.1 # 4 7.0 25.40 13.0
print(df.dtypes) # Printing the data types of all columns # A float64 # B float64 # C float64 # dtype: object |
print(df.dtypes) # Printing the data types of all columns # A float64 # B float64 # C float64 # dtype: object
Example 1: Transforming One Column of a pandas DataFrame from Float to String
df1 = df.copy() # Duplicate pandas DataFrame df1['A'] = df1['A'].astype(str) # Converting float to string |
df1 = df.copy() # Duplicate pandas DataFrame df1['A'] = df1['A'].astype(str) # Converting float to string
print(df1.dtypes) # Printing the data types of all columns # A object # B float64 # C float64 # dtype: object |
print(df1.dtypes) # Printing the data types of all columns # A object # B float64 # C float64 # dtype: object
Example 2: Transforming Multiple Columns of a pandas DataFrame from Float to String
df2 = df.copy() # Duplicate pandas DataFrame df2 = df2.astype({'A': str, 'C': str}) # Converting float to string |
df2 = df.copy() # Duplicate pandas DataFrame df2 = df2.astype({'A': str, 'C': str}) # Converting float to string
print(df2.dtypes) # Printing the data types of all columns # A object # B float64 # C object # dtype: object |
print(df2.dtypes) # Printing the data types of all columns # A object # B float64 # C object # dtype: object
Example 3: Transforming Each Column of a pandas DataFrame from Float to String
df3 = df.copy() # Duplicate pandas DataFrame df3 = df3.astype(str) # Converting float to string |
df3 = df.copy() # Duplicate pandas DataFrame df3 = df3.astype(str) # Converting float to string
print(df3.dtypes) # Printing the data types of all columns # A object # B object # C object # dtype: object |
print(df3.dtypes) # Printing the data types of all columns # A object # B object # C object # dtype: object
Further Resources
Have a look at the following Python programming tutorials. They illustrate similar topics as this post.