您可以使用以下命令将字符串数组转换为浮点数组(带有 NaN)np.genfromtxt https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.genfromtxt.html:
In [83]: np.set_printoptions(precision=3, suppress=True)
In [84]: np.genfromtxt(np.array(['1','2','3.14','1e-3','b','nan','inf','-inf']))
Out[84]: array([ 1. , 2. , 3.14 , 0.001, nan, nan, inf, -inf])
这是识别“数字”字符串的方法:
In [34]: x
Out[34]:
array(['1', '2', 'a'],
dtype='|S1')
In [35]: x.astype('unicode')
Out[35]:
array([u'1', u'2', u'a'],
dtype='<U1')
In [36]: np.char.isnumeric(x.astype('unicode'))
Out[36]: array([ True, True, False], dtype=bool)
请注意,“数字”表示仅包含数字字符的 Unicode,即具有 Unicode 数字值属性的字符。确实如此not包括小数点。所以u'1.3'
不被视为“数字”。