Open In App

How to Convert String to Float in Pandas DataFrame

Improve
Improve
Like Article
Like
Save
Share
Report

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:

dataframe

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:

DataFrame.astype() 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:

pandas.to_numeric() output
Error Handling

Sometimes, we may not have a float value represented as a string. So, pd.to_numeric() function will show an error. To remove this error, we can use errors=’coerce’, to convert the value at this position to be converted to NaN. 

Python3




# importing pandas as pd
import pandas as pd
 
# dictionary
Data = {'Year': ['2016', '2017',
                 '2018', '2019'],
         'Inflation Rate': ['4.47', '5',
                           'No data', '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'],
                                     errors = 'coerce')
 
# show the dataframe
print(df)
 
# show the data types
print (df.dtypes)


Output: 

pandas.to_numeric() error handling

Note: String data type shows as an object.

Conclusion

Converting string to float data type enables us to perform arithmetic operations on the value and make graphical representations. String values are not very useful in data analysis, but changing them to float will provide much more value in your data analysis project.

In this tutorial, we have covered the DataFrame.astype() and pandas.to_numeric() functions to convert string values to float in Pandas DataFrame. We have also shown the method to handle any possible errors you might face. After completing this guide, you will have no problem converting string values to float in a DataFrame.



Last Updated : 18 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads