Transforming one kind of data type to another kind in Python involves the use of various functions. This article aims to provide details on how to convert a string to a float. The float() function in Python can be used to convert a string to a float. It’s a built-in feature for converting a floating-point number to an entity. Internally, the float() function calls the float() function of the defined item.
A string is a one- or more-character sequence (letters, numbers, symbols). Strings are a common type of data in computer programs. We need to convert strings to numbers or numbers to strings regularly, especially when dealing with user-generated data.
A function in Python converts a number string to a floating-point number.
Floats, integer, or string are extremely useful. Generally, it has to be in the correct decimal format if it’s a string. As a result, it gives you a floating object.
ValueError is raised on the off chance that the given string has something other than a floating-point representation of a number. But, if no argument is given, 0.0 is returned. On the other hand, Overflow Error is raised if the given statement is beyond the float range.
How to convert a string to float in Python
Let’s look at a basic Python example of converting a string to a float.
string_val = '146.9856' float_val = float(string_val) print(type(float_val)) print ('Float Value =', float_val )
What is the purpose of converting a string to a float?
If we get a float value from user input through the terminal or reading it from a file, they are string objects. As a result, we must precisely convert them to float to perform required operations such as addition, multiplication, and so on.
# input_through_terminal.py # get a float value from user input through the terminal string_input_1 = input('Input the first floating point value:\n') float_input_1 = float(string_input_1) string_input_2 = input('Input the second floating point value:\n') float_input_2 = float(string_input_2) print(f'Sum of {string_input_1} and {string_input_2} is {float_input_1+float_input_2}')
The float () function
You can convert virtually any data type to a floating-point number using this function. The syntax is as follows:
float (x)
Only one parameter is accepted by the method. However, it is optional. If no argument is given, the resultant value from this method is 0.0.
Example 1: convert string to float
input_string= "821.672" print(input_string) print(type(input_string)) # converting the string variable to a float value resultant_float = float(input_string) print(resultant_float ) print(type(resultant_float ))
Example 2: convert string to float
input_string = '278.772' resultant_float = float(input_string) print(type(resultant_float )) print('Float Value =', resultant_float )
Float number conversion from a decimal string
The float class can be used to convert a decimal string to a float number. As an example, consider the following:
The following is the code for transforming a string using float:
#demonstrating converting a string to float str_val_1 = '25.58' b_val = 14.66 c_val= float(str_val_1) + b_val print ("The value of c_val = ",c_val)
Note that attempting to use the int here would result in an error.
converting a decimal list to a float in for list objects
Similarly, instead of int, you can use float to convert a list of decimal number strings. Here’s an example:
Example 1: converting a decimal list to a float in for list objects
#demonstrating string to float in a list string_list = ['34.712', '12.36', '387.49', '89.09', '156.60'] float_list = [float(val) for val in string_list] print (float_list)
Example 2: converting a decimal list to a float in for list objects
number_list = ["8.88","6.66","1.11","4.44","9.99"] float_list = [ float(float_val) for float_val in number_list] print(number_list) print(float_list)
Example 3: converting a decimal list to a float in for list objects
#convert_decimal_list_float.py number_list = ["8.88","6.66","1.11","4.44","9.99"] sum = 0 for x in number_list : sum += float(x) print(sum)
Convert a comma-separated number string to a floating object
Let’s say we have a string called “10,974.76,” which includes the number and commas. Converting this type of string to float is somewhat tricky.
We will get an error whenever we make attempts to transfer it to the function float() directly. As an example,
string_val = "10,974.76," num_val = float(string_val)
float() returned an error since the string contained characters other than digits. So, before passing the string to the float() function, we need to delete all the extra commas. As an example,
conversion of a string value with a comma to float value
string_val = "10,974.76" num_val = float(string_val.replace(',', '')) print(num_val) print(type(num_val))
Method to ascertain if a string is a floating
def check_is_float(val): try: float(val) return True except: return False
When the above method is run for each of the following string values, the results are represented below.
String value | Status | Description |
“.1” | True | mantissa only |
“123.E4” | True | Exponential notation |
“-iNF” | True | Negative infinity |
“NaNanananaBATMAN” | False | I am Batman |
“NaN” | True | Not a number |
“\t\n12\r\n” | True | whitespace ignored |
” -127 “ | True | Spaces trimmed |
“” | False | Blank string |
“127” | True | Passed string |
True | True | Pure sweet Truth |
“123.456” | True | Decimal |
False | True | So false it becomes true |
“True” | False | Vile contemptible lie |
“(1)” | False | Parenthesis is bad |
“-+1” | False | Make up your mind |
“+1e1.3” | False | No decimals in exponent |
“+1e1^5” | False | Fancy exponent not interpreted |
“+1e1” | True | Plus is OK with exponent |
“-5e-5” | True | Raise to a negative number |
0**0 | True | 0___0 Exponentiation |
“0E0” | True | Exponential, move dot 0 places |
“1,234” | False | Commas gtfo |
u’\x30′ | True | Unicode is fine. |
“NULL” | False | Null is not special |
0x3fade | True | Hexadecimal |
“6e7777777777777” | True | Shrunk to infinity |
“1.797693e+308” | True | This is max value |
“infinity” | True | Same as inf |
“infinityandBEYOND” | False | Extra characters wreck it |
“12.34.56” | False | Only one dot allowed |
u’å››’ | False | Japanese ‘4’ is not a float. |
“#56” | False | Pound Sign |
“56%” | False | Percent of what? |
fastnumbers
fastnumbers is a module with three goals in decreasing order of importance as to why the module was created:
Provide a set of utility functions that wrap the above int and float replacements and provide error handling that is simple, concise, efficient, quick, and versatile.
Provide a collection of functions for quickly determining if an input can be converted to an int or a float.
Provide drop-in replacements for Python’s built-in int and float up to 2 times faster on average. Except for a few unique corner-cases specified in the API documentation for those functions, these functions should behave exactly like the Python built-ins.
pip install fastnumbers
from fastnumbers import fast_real fast_real("876.623623") type(fast_real("89.7567")) fast_real("mine") type(fast_real("345"))
In a Pandas DataFrame, how do you convert strings to floats?
To convert strings to floats in a Pandas DataFrame, you can use one of the two methods below, depending on the situation:
(1) astype(float)
df['DataFrame Column'] = df['DataFrame Column'].astype(float)
(2) to_numeric
df['DataFrame Column'] = pd.to_numeric(df['DataFrame Column'],errors='coerce')
Here, you’ll learn how to convert strings to floats in three different ways:
- For a column containing both numeric and non-numeric values
- For a column containing both numeric and non-numeric values
- For a complete DataFrame
Converting Strings to Floats in Pandas DataFrame Scenarios
Scenario 1: Strings are used to store numerical values
Let’s make a DataFrame with just two columns to keep things simple.
The code for creating the DataFrame in Python is shown below. Herein, the ‘Cost’ column values are stored as strings (with single quotes around them). Notice that the same principles would apply if double quotes were used instead of single quotes):
import pandas as pd my_data = {'Item': ['EFG','JKL'], 'Cost': ['250','270'] } _df = pd.DataFrame(my_data) print (_df) print (_df.dtypes)
The aim is to make floats out of the values in the ‘Cost’ column.
The conversion into floats can then be done using the astype(float) method:
df['DataFrame Column'] = df['DataFrame Column'].astype(float)
The ‘Cost’ column is the ‘DataFrame Column’ in the sense of our example. As a result, the complete code to convert the values to floats is:
import pandas as pd my_data = {'Item': ['EFG','JKL'], 'Cost': ['250','270'] } _df = pd.DataFrame(my_data) _df['Cost'] = _df['Cost'].astype(float) print (_df) print (_df.dtypes)
Scenario 2: Numeric and non-numeric values
Build a new DataFrame with two columns (‘Item’ and ‘Cost’). This time, however, the values in the ‘Cost’ column will include both numeric and non-numeric data:
In Python, this is how the DataFrame will look:
import pandas as pd my_data = {'Item': ['WWW','KKK','RRR','FFF'], 'Cost': ['620','EFG860','590','135GHL'] } _data_frame = pd.DataFrame(my_data) print (_data_frame) print(_data_frame.dtypes)
The data form for the ‘Cost’ column is the same as before: Object.
After that, you can use the to_numeric method to convert the values in the ‘Cost’ column to floats as follows:
df['DataFrame Column'] = pd.to_numeric(df['DataFrame Column'], errors='coerce')
You can convert non-numeric values to NaN by setting errors=’coerce’.
For your convenience, below is the complete code:
import pandas as pd my_data = {'Item': ['WWW','KKK','RRR','FFF'], 'Cost': ['620','EFG860','590','135GHL'] } _data_frame = pd.DataFrame(my_data) _data_frame['Cost'] = pd.to_numeric(_data_frame['Cost'], errors='coerce') print (_data_frame) print(_data_frame.dtypes)
To go even further, you can use df.replace to replace the ‘NaN’ values with ‘0’ values.
import pandas as pd import numpy as np my_data = {'Item': ['WWW','KKK','RRR','FFF'], 'Cost': ['620','EFG860','590','135GHL'] } _data_frame = pd.DataFrame(my_data) _data_frame['Cost'] = pd.to_numeric(_data_frame['Cost'], errors='coerce') _data_frame = _data_frame.replace(np.nan, 0, regex=True) print (_data_frame) print(_data_frame.dtypes)
Scenario 3: Convert Strings to Floats, Under the Entire DataFrame
Let’s make a DataFrame with three columns in which all of the values are stored as strings (in single quotes) for the final scenario:
import pandas as pd my_data = {'Cost_1': ['520','850','300','470','220'], 'Cost_2': ['750','370','590','980','310'], 'Cost_3': ['350','840','240','190','930'] } _data_frame = pd.DataFrame(my_data) print (_data_frame) print (_data_frame.dtypes)
From what you have observed, the entirety of the columns in the DataFrame have the same data type: object.
You can then use the following syntax to convert all of the values in the DataFrame to floats:
df = df.astype(float)
As a result, the complete Python code for performing the conversion will be as follows:
import pandas as pd my_data = {'Cost_1': ['520','850','300','470','220'], 'Cost_2': ['750','370','590','980','310'], 'Cost_3': ['350','840','240','190','930'] } _data_frame = pd.DataFrame(my_data) _data_frame = _data_frame.astype(float) print (_data_frame) print (_data_frame.dtypes)
Final Thoughts
This article has shown how to use built-in methods to convert a string native data type to a float data type. In Python, being able to transform data types gives you more flexibility when writing programs. We learned how to change a string value to a float in this tutorial. If we’re not sure what the receiving values are, it’s a good coding practice to convert them first.