Let’s see how to get an array from a string in the Numpy Python library.
Use Numpy and StringIO
To create a Numpy array, we will need to import both Numpy and StringIO.
StringIO will allow us to read the string properly.
Numpy will allow us to generate an array.
Example Python code reads my_string and generates a Numpy array.
import numpy as np from io import StringIO my_string = StringIO('1.3, 2.1, 3.2, 5.26, 7.6, 8.12') string_array = np.genfromtxt(my_string, delimiter=',', dtype='float') print(f"My array created based on string: \n {string_array}")
The Numpy genfromtxt function takes my_string as a parameter.
The second parameter is a delimiter, which was a comma in my example.
Also, I chose float as a dtype.