Convert a list of strings to float numbers in Python?

Problem:

We would like to change the data type of all elements in a Python list from string to floating.

Solution:

We have three methods to convert a list of strings to float using Python programming. Let us proceed to look at the code and the output for each method.

Use Python for loops

Using the For loop, we iterate through all the values inside the string list, convert each value to float, and store the converted values to a new variable.

Code:

num_string = ["0.1", "0.2", "0.3", "0.4", "0.5"]
num_float = []
print("Before conversion: ",num_string)
for values in num_string:
    num_float.append(float(values))
print("Converted values: ",num_float)
print("Type: ",type(num_float[1]))

Output:

Before conversion:  ['0.1', '0.2', '0.3', '0.4', '0.5']
Converted values:  [0.1, 0.2, 0.3, 0.4, 0.5]
Type:  <class 'float'>

Use the Python map command

Instead of using for loop, we can use the mapping technique to apply a function to all the elements in a sequence.

Code:

num_string = ["0.1", "0.2", "0.3", "0.4", "0.5"]
num_float = list(map(float, num_string))
print("Before conversion: ",num_string)
print("Converted values: ",num_float)
print("Type: ",type(num_float[3]))

Output:

Before conversion:  ['0.1', '0.2', '0.3', '0.4', '0.5']
Converted values:  [0.1, 0.2, 0.3, 0.4, 0.5]
Type:  <class 'float'>

Using Numpy (Data Analysis Third-party package)

Numpy is a package that is part of the Python Data Analysis / Data Science stack. NumPy is used to work with multidimensional arrays. In this example we’ll use Numpy to convert the string values to float.

Note:

Before we use the code, we first need to install the package NumPy to import the package to the code. You can install NumPy using the PIP command utility. NumPy is delivered by default with the Anaconda distribution.

Once you import NumPy, open the command prompt and enter the code below:

Code:

import numpy as np  
num_string = ["0.1", "0.2", "0.3", "0.4", "0.5"]
num_float = np.array(num_string, dtype=float)
print("Before conversion: ",num_string)
print("Converted values: ",num_float)
print("Type: ",type(num_float[2]))

Output:

Before conversion:  ['0.1', '0.2', '0.3', '0.4', '0.5']
Converted values:  [0.1 0.2 0.3 0.4 0.5]
Type:  <class 'numpy.float64'>

That is all we have for today. Thank you! Happy coding!