NumPy: numpy.fromstring() function
numpy.fromstring() function
The numpy.fromstring() function is used to create a one-dimensional array from a string of data. The string is interpreted as binary data, and each character in the string represents a single element in the resulting array.
Syntax:
numpy.fromstring(string, dtype=float, count=-1, sep='')
Parameters:
Name | Description | Required / Optional |
---|---|---|
string | A string containing the data. | Required |
dtype | The data type of the array; default: float. For binary input data, the data must be in exactly this format | Optional |
count | Read this number of dtype elements from the data. If this is negative (the default), the count will be determined from the length of the data. | Optional |
sep | The string separating numbers in the data; extra whitespace between elements is also ignored. | Optional |
Return value:
arr [ndarray]
The constructed array.
Raises:
ValueError If the string is not the correct size to satisfy the requested dtype and count.
Example: Creating an array from a string using np.fromstring()
>>> import numpy as np
>>> np.fromstring('3 5', dtype=int, sep=' ')
array([3, 5])
In the above code the string "3, 5" is passed as the first argument to np.fromstring(), which specifies the data to be used to create the array. The dtype argument is used to specify the data type of the resulting array, which is set to int. The sep argument is used to specify the separator used to split the string into individual values. In this case, the separator is set to , to indicate that the values in the string are separated by commas. The resulting output is the NumPy array [3, 5].
Pictorial Presentation:
Python - NumPy Code Editor:
Previous: fromiter()
Next: loadtxt()
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/numpy/array-creation/fromstring.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics