You can directly work with the string and convert it back to numpy array using np.array and split, like this:
>>> np.array('1 2 3.1415'.split(' '), dtype=float)
array([ 1. , 2. , 3.1415])
>>> np.array('not a string'.split(' '), dtype=float)
ValueError: could not convert string to float: not
When using fromstring, if your input string does not contain only real valued data, you should expect an empty array.
>>> np.fromstring('not a string', dtype=float, sep=' ')
array([], dtype=float64)
>>> np.fromstring('not a string 5', dtype=float, sep=' ')
array([], dtype=float64)
>>> np.fromstring('8 5', dtype=float, sep=' ')
array([ 8., 5.])
EDIT:
You can implement your own .fromstring by verifying your input_string format. If it does have the pattern that you are looking for (in your case all floats), then convert it to numpy.array. In case of failure, you either want to explicitly through an exception error, or return an empty list.
In [1]: import re
In [2]: import numpy as np
In [3]: def my_fromstring(input_string):
...: input_string = input_string.strip()
...: input_string = re.sub(' +', ' ', input_string)
...: float_pattern = '\d+\.d+|\d+'
...: verify_fn = lambda s: map(lambda x: re.match(float_pattern, x),
...: s.split(' '))
...: pattern_match_fn = lambda x: any(map(lambda x: True if x == None
...: else False, x))
...: res = verify_fn(input_string)
...: match = pattern_match_fn(res)
...: if not match:
...: return np.array(map(float, input_string.split(' ')))
...: else:
...: raise ValueError('Incorrect input format')
...:
You can now use your custom function to check:
In [4]: my_fromstring(' 7 5 8 3 ')
Out[4]: array([ 7., 5., 8., 3.])
In [5]: my_fromstring('not a string')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-67-88cd38f7ad26> in <module>()
----> 1 my_fromstring('not a string')
<ipython-input-65-e355cf28acb0> in my_fromstring(input_string)
10 return np.array(map(float, input_string.split(' ')))
11 else:
---> 12 raise ValueError('Incorrect input format')
13
ValueError: Incorrect input format