Convert Float to String in pandas DataFrame Column in Python (4 Examples) | Using astype() & apply()

Published: 03 April 2023
on channel: Statistics Globe
1,077
18

How to convert a float column to the string data type in a pandas DataFrame in the Python programming language. More details: https://statisticsglobe.com/convert-f...
Python code of this video:

import pandas as pd # Load pandas

data = pd.DataFrame({'x1':[1.1, 2.2, 3.3, 4.4, 5.5], # Create pandas DataFrame
'x2':[1.5, 2.5, 3.5, 4.5, 5.5],
'x3':[0.1, 0.2, 0.3, 0.4, 0.5]})
print(data) # Print pandas DataFrame

print(data.dtypes) # Check data types of columns
x1 float64
x2 float64
x3 float64
dtype: object

data_new1 = data.copy() # Create copy of DataFrame
data_new1['x1'] = data_new1['x1'].astype(str) # Transform float to string

print(data_new1.dtypes) # Check data types of columns
x1 object
x2 float64
x3 float64
dtype: object

data_new2 = data.copy() # Create copy of DataFrame
data_new2 = data_new2.astype({'x2': str, 'x3': str}) # Transform multiple floats to string

print(data_new2.dtypes) # Check data types of columns
x1 float64
x2 object
x3 object
dtype: object

data_new3 = data.copy() # Create copy of DataFrame
data_new3 = data_new3.astype(str) # Transform all columns to string

print(data_new3.dtypes) # Check data types of columns
x1 object
x2 object
x3 object
dtype: object

data_new4 = data.copy() # Create copy of DataFrame
data_new4['x1'] = data_new4['x1'].apply(str) # Transform string to float

print(data_new4.dtypes) # Check data types of columns
x1 object
x2 float64
x3 float64
dtype: object

Follow me on Social Media:
Facebook – Statistics Globe Page:   / statisticsglobecom  
Facebook – R Programming Group for Discussions & Questions:   / statisticsglobe  
Facebook – Python Programming Group for Discussions & Questions:   / statisticsglobepython  
LinkedIn – Statistics Globe Page:   / statisticsglobe  
LinkedIn – R Programming Group for Discussions & Questions:   / 12555223  
LinkedIn – Python Programming Group for Discussions & Questions:   / 12673534  
Twitter:   / joachimschork  

Music by bensound.com


On this page of the site you can watch the video online Convert Float to String in pandas DataFrame Column in Python (4 Examples) | Using astype() & apply() with a duration of online in good quality, which was uploaded by the user Statistics Globe 03 April 2023, share the link with friends and acquaintances, this video has already been watched 1,077 times on youtube and it was liked by 18 viewers. Enjoy your viewing!