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.
Key takeaways
You can use the genfromtxt function to get an array from a string in NumPy.
The genfromtxt function takes a number of parameters, including the delimiter, the dtype, and the skip_lines parameter.
The delimiter parameter specifies the character that separates the values in the string.
The dtype parameter specifies the data type of the values in the array.
The skip_lines parameter specifies the number of lines to skip at the beginning of the string before the array is generated.