How to Convert Strings to Floats in Pandas DataFrame?

28 Jul, 2020
In this article, we’ll look at different ways in which we can convert a string to a float in a pandas dataframe. Now, let’s create a Dataframe with ‘Year’ and ‘Inflation Rate’ as a column.
Python3
# importing pandas libraryimport pandas as pd  # dictionaryData = {'Year': ['2016', '2017',                  '2018', '2019'],        'Inflation Rate': ['4.47', '5',                            '5.98', '4.1']}# create a dataframedf = pd.DataFrame(Data)  # show the dataframeprint (df)  # show the datatypesprint(df.dtypes)
Output:
Method 1: Using DataFrame.astype().
The method is used to cast a pandas object to a specified dtype. 
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 ‘Inflation Rate’ column to float.
Python3
# importing pandas libraryimport pandas as pd  # dictionaryData = {'Year': ['2016', '2017',                  '2018', '2019'],        'Inflation Rate': ['4.47', '5',                            '5.98', '4.1']}# create a dataframedf = pd.DataFrame(Data)  # converting each value # of column to a stringdf['Inflation Rate'] = df['Inflation Rate'].astype(float)  # show the dataframeprint(df)  # show the datatypesprint (df.dtypes)
Output:
Method 2: Using pandas.to_numeric() function.
The function is used to convert the argument to a numeric type. 
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 1: In this example, we’ll convert each value of ‘Inflation Rate’ column to float.
Code:
Python3
# importing pandas libraryimport pandas as pd  # creating a dictionaryData = {'Year': ['2016', '2017',                  '2018', '2019'],          'Inflation Rate': ['4.47', '5',                              '5.98', '4.1']}# create a dataframedf = pd.DataFrame(Data)  # converting each value of column to a stringdf['Inflation Rate'] = pd.to_numeric(df['Inflation Rate'])  # show the dataframeprint(df)  # show the data typesprint (df.dtypes)
Output: 
Example 2: 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. 
Code: 
Python3
# importing pandas as pdimport pandas as pd  # dictionaryData = {'Year': ['2016', '2017',                 '2018', '2019'],         'Inflation Rate': ['4.47', '5',                            'No data', '4.1']}  # create a dataframedf = pd.DataFrame(Data)  # converting each value of column to a stringdf['Inflation Rate'] = pd.to_numeric(df['Inflation Rate'],                                     errors = 'coerce')  # show the dataframeprint(df)  # show the data typesprint (df.dtypes)
Output: 
Note: String data type shows as an object.
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts