How to Convert String to Float in Pandas DataFrame
There are two methods to convert string to float data type in Pandas DataFrame – DataFrame.astype() and pandas.to_numeric() function.
DataFrame.astype() function enables you to convert Pandas objects to any data type whereas pandas.to_numeric() function lets you convert into int or float data type only.
Let’s look at both methods to convert string to float in DataFrame with examples:
Convert String to Float in DataFrame Using DataFrame.astype()
DataFrame.astype() method is used to cast a Pandas object to a specified datatype.
Syntax: DataFrame.astype(self: ~ FrameOrSeries, dtype, copy: bool = True, errors: str = ‘raise’)
Returns: casted: type of caller
Example: In this example, we’ll convert each value of the ‘Inflation Rate’ column to float.
Python3
# importing pandas library import pandas as pd # dictionary Data = { 'Year' : [ '2016' , '2017' , '2018' , '2019' ], 'Inflation Rate' : [ '4.47' , '5' , '5.98' , '4.1' ]} # create a dataframe df = pd.DataFrame(Data) # converting each value # of column to a string df[ 'Inflation Rate' ] = df[ 'Inflation Rate' ].astype( float ) # show the dataframe print (df) # show the datatypes print (df.dtypes) |
Output:
Convert String to Float in DataFrame Using pandas.to_numeric()
pandas.to_numeric() function is used to convert the argument to a numeric type (int or float).
Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None)
Returns: numeric if parsing succeeded. Note that the return type depends on the input. Series if Series, otherwise ndarray.
Example: In this example, we’ll convert each value of the ‘Inflation Rate’ column to float.
Python3
# importing pandas library import pandas as pd # creating a dictionary Data = { 'Year' : [ '2016' , '2017' , '2018' , '2019' ], 'Inflation Rate' : [ '4.47' , '5' , '5.98' , '4.1' ]} # create a dataframe df = pd.DataFrame(Data) # converting each value of column to a string df[ 'Inflation Rate' ] = pd.to_numeric(df[ 'Inflation Rate' ]) # show the dataframe print (df) # show the data types print (df.dtypes) |
Output:
How to Convert String to Float in Pandas DataFrame
Converting Strings to Float in Pandas DataFrame is a very crucial step for data analysis. Converting string to float values can help you perform various arithmetic operations and plot graphs.
In this article, we’ll look at different ways to convert a string to a float in DataFrame.
Creating Sample Dataframe
Now, let’s create a DataFrame with ‘Year’ and ‘Inflation Rate’ as a column. We will be using this DataFrame in upcoming examples:
Python3
# importing pandas library import pandas as pd # dictionary Data = { 'Year' : [ '2016' , '2017' , '2018' , '2019' ], 'Inflation Rate' : [ '4.47' , '5' , '5.98' , '4.1' ]} # create a dataframe df = pd.DataFrame(Data) # show the dataframe print (df) # show the datatypes print (df.dtypes) |
Output:
Contact Us