您可以直接與字符串工作,並使用np.array
和split
,像這樣將其轉換回numpy的數組:
>>> 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
當使用fromstring
,如果你輸入的字符串不包含唯一的真正價值數據,你應該期望一個空數組。
>>> 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.])
編輯: 您可以實現自己的.fromstring
通過驗證您的input_string
格式。如果它確實有你正在尋找的模式(在你的情況下所有浮動),然後將其轉換爲numpy.array
。如果發生故障,您要麼顯式地通過異常錯誤,要麼返回空列表。
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')
...:
您現在可以使用自定義功能進行檢查:
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
嘗試'np.fromstring('not a string',dtype = float,sep ='')',這會返回'array([ - 1。])''。 –
如果你知道你的輸入數據格式,你可以應用'strip'功能,你仍然可以得到想要的輸出。 –
'np.array(s.split(),dtype = float)'如果不能將其中一個'words'轉換爲float,將會拋出一個錯誤。 – hpaulj