Python String to float, float to String

Python String To Float, Float To String

In this article, we will be dealing with the conversion of Python String to float and vice-versa. In the daily programming practices, many times we come across scenarios wherein we feel the need to convert the type of data we are dealing with.

Python String to float

Python provides us with the built-in float() method to convert the data type of input from String to float.

Syntax:

float(input_string)

Example:

inp = '99.23'
print("Input string:\n",inp)
opt = float(inp)


print('Input value after converting it to float type:\n',opt)
print(type(opt))

Output:

Input string:
 99.23
Input value after converting it to float type:
 99.23
<class 'float'>

Python NumPy String to float

NumPy module has got astype() method to convert the type of data.

The astype() method converts the type of the input data to the data type specified in the parameter.

Syntax:

input_string.astype(numpy.float)

Example:

import numpy
inp = numpy.array(["76.5", "75.5", "75.7"]) 

print ("Input array:\n")
print(str(inp)) 

opt = inp.astype(numpy.float) 

print ("Output array after conversion:\n")
print(str(opt)) 

Output:

Input array:

['76.5' '75.5' '75.7']
Output array after conversion:

[ 76.5  75.5  75.7]


Pandas String to float

Pandas module also uses astype() function to convert the data type of a particular field of the data set to the specified type.

Syntax:

input.astype(float)

Input csv file:

Input csv file
Input File

Example:

import pandas
import numpy
inp = pandas.read_csv('C:\\Users\\HP\\Desktop\\Book1.csv')
print(inp.dtypes)
inp['Value'] = inp['Value'].astype(float)
print(inp)
print(inp.dtypes)

Output:

Details     object
Value      float64
dtype: object

           Details  Value
0        John:Pune  21.00
1      Bran:satara  22.00
2      Sam:Chennai  85.24
3       RHEY:Delhi  12.00
4  CRANNY:Karnatak  25.26

Details     object
Value      float64
dtype: object

Python float to String

Python String has built-in str() method to convert the input data of any type to the String form.

Syntax:

str(input)

Example:

inp = 77.77
print(inp)
print(type(inp))

opt = str(inp)
print(opt)
print(type(opt))

Output:

77.77
<class 'float'>
77.77
<class 'str'>

Python NumPy float to String

List Comprehension can be used to convert Python NumPy float array to an array of String elements.

Syntax:

["%.2f" % i for i in input_array]

Example:

import numpy
inp = numpy.array([77.75, 77.25, 77.55])
print("Input array:\n",inp)
opt =["%.2f" % i for i in inp]
print("Converted array to string:\n")
print(opt)

In the above snippet of code, “%.2f” will give me precision up to two decimals in the output array.

Output:

Input array:
 [77.75 77.25 77.55]
Converted array to string:
['77.75', '77.25', '77.55']

Conclusion

In this article, we have understood the conversion of data from String to float form and vice-versa with Python Data structures.


References