Convert String Array to Numpy Float Array

Lets say you have array of strings and wants to convert it to Numpy float array, then how you will do that. In this tutorial you will learn all the steps require to Convert String Array to Numpy Float Array.

Steps to Convert String Array to Numpy Float Array

You can convert a string array to a NumPy float array in Python, using thenumpy.array function and specify the data type as float. Below are the steps.

Step 1: Import NumPy

Before you can use NumPy, you need to import it. Import it using the import statement.

import numpy as np

Step 2: Create a sample String Array

Assume you have a string array that you want to convert. You can crate string array using the double quotes for elements and square bracker.

string_array = ["10.1", "20.2", "30.3", "40.4"]

Step 3: Convert String Array to NumPy Float Array


Use the numpy.array function to convert the string array to a NumPy float array. In this example, dtype=float specifies that the resulting NumPy array should have elements of type float and it will be argument for the numpy.array() function.

float_array = np.array(string_array, dtype=float)

Here’s the complete code

import numpy as np

# Step 2: Create a String Array
string_array = ["10.1", "20.2", "30.3", "40.4"]

# Step 3: Convert String Array to NumPy Float Array
float_array = np.array(string_array, dtype=float)

print(float_array)

Output

[10.1 20.2 30.3 40.4]

Now, float_array is a NumPy array with elements of type float. It comes from converted original string array. You can Adjust the string_array variable to match your actual data.

Conclusion

You can easily convert the array or list of strings to numpy float array using the numpy.array() function. You have to just pass the dtype=”float” argument to the array() function. The above steps will easily Convert String Array to Numpy Float Array.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link