What is the numpy.fromstring() function from NumPy in Python?
Overview
In Python, the fromstring() function is used to
create a new 1D (one-dimensional) array from a string that contains data.
Syntax
numpy.fromstring(string, dtype=float, sep)
Parameter value
The fromstring() function takes the following parameter values:
string: This represents the string that contains the data.dtype: This represents the data type of the desired array. This parameter is optional.sep: This represents the string that separates the numbers. The extra white space between the elements of the string is ignored. This parameter is optional.
Return value
The fromstring() function returns an output 1D array.
Code example
import numpy as np# creating a string containing datamystring = "1, 2, 3"# implementing the fromstring() functionmyarray = np.fromstring(mystring, dtype = int, sep = "," )print(myarray)
Code explanation
- Line 1: We import the
numpymodule. - Line 4: We create a string variable called
mystring. - Line 7: We implement the
fromstring()function on the string variablemystringwithintas the data type and a comma (,), since we separate our strings with a comma. We assign the output to another variable calledmyarray. - Line 9: We print the new
1Darray calledmyarray.