convert string to float in Python-min

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 )
How to convert a string to float in Python
How to convert a string to float in Python

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}')
get a float value from user input through the terminal

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 1: convert string to float
Example 1: convert string to 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 )

Example 2: convert string to float
Example 2: convert string to 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)
Float number conversion from a decimal string
Float number conversion from a decimal string

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 1: converting a decimal list to a float in for list objects
Example 1: converting a decimal list to a float in for list objects

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 2: converting a decimal list to a float in for list objects
Example 2: converting a decimal list to a float in for list objects

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)
Example 3: converting a decimal list to a float in for list objects
Example 3: converting a decimal list to a float in for list objects

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)
error when converting a string which includes the number and commas to a float
error when converting a string which includes the number and commas to a float

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))
conversion of a string value with a comma to float value
conversion of a string value with a comma to float value

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 valueStatusDescription
“.1”Truemantissa only
“123.E4”TrueExponential notation
“-iNF”TrueNegative infinity
“NaNanananaBATMAN”FalseI am Batman
“NaN”TrueNot a number
“\t\n12\r\n”Truewhitespace ignored
” -127 “TrueSpaces trimmed
“”FalseBlank string
“127”TruePassed string
TrueTruePure sweet Truth
“123.456”TrueDecimal
FalseTrueSo false it becomes true
“True”FalseVile contemptible lie
“(1)”FalseParenthesis is bad
“-+1”FalseMake up your mind
“+1e1.3”FalseNo decimals in exponent
“+1e1^5”FalseFancy exponent not interpreted
“+1e1”TruePlus is OK with exponent
“-5e-5”TrueRaise to a negative number
0**0True0___0 Exponentiation
“0E0”TrueExponential, move dot 0 places
“1,234”FalseCommas gtfo
u’\x30′TrueUnicode is fine.
“NULL”FalseNull is not special
0x3fadeTrueHexadecimal
“6e7777777777777”TrueShrunk to infinity
“1.797693e+308”TrueThis is max value
“infinity”TrueSame as inf
“infinityandBEYOND”FalseExtra characters wreck it
“12.34.56”FalseOnly one dot allowed
u’四’FalseJapanese ‘4’ is not a float.
“#56”FalsePound Sign
“56%”FalsePercent 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"))
fastnumbers
fastnumbers

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)
Scenario 1: Strings are used to store numerical values
Scenario 1: Strings are used to store numerical values

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 1: Cost converted to float
Scenario 1: Cost converted to float
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)
Scenario 2: Numeric and non-numeric values before conversion
Scenario 2: Numeric and non-numeric values before conversion

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)
Scenario 2: Numeric and non-numeric values before conversion
Scenario 2: Numeric and non-numeric values after conversion

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 2: Numeric and non-numeric values  and replace after conversion
Scenario 2: Numeric and non-numeric values and replace after conversion
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)
Scenario 3:  Convert Strings to Floats, Under the Entire DataFrame
Scenario 3: Convert Strings to Floats, Under the Entire DataFrame

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)
convert all of the values in the DataFrame to floats using df.dastype()
convert all of the values in the DataFrame to floats using df.dastype()

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.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *