Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,无法将字符串转换为浮点:';7a和x27;_Python_Arrays_Python 3.x_List_Numpy - Fatal编程技术网

Python,无法将字符串转换为浮点:';7a和x27;

Python,无法将字符串转换为浮点:';7a和x27;,python,arrays,python-3.x,list,numpy,Python,Arrays,Python 3.x,List,Numpy,我有以下NumPy字符串数组 array(['cwp+17', 'cn95', 'awd+12', ..., 'dgb+19', 'mbc+19', 'acd+19'] 为了得到数字部分,我对这个数组进行了如下切片 RA = [x[-2:] for x in RA] RA = np.asarray(RA) 现在看起来像这样 array(['17', '95', '12', ..., '19', '19', '19'], dtype='<U2') 数组(['17','95','12',

我有以下NumPy字符串数组

array(['cwp+17', 'cn95', 'awd+12', ..., 'dgb+19', 'mbc+19', 'acd+19']
为了得到数字部分,我对这个数组进行了如下切片

RA = [x[-2:] for x in RA]
RA = np.asarray(RA)
现在看起来像这样

array(['17', '95', '12', ..., '19', '19', '19'], dtype='<U2')

数组(['17','95','12',…,'19','19','19'],dtype='其中一个字符串以
7a
结尾,这不是一个有效的数字。示例中的
..
隐藏了这个问题。编写一个函数比较容易,该函数使用以数字开头的双字符字符串,其第二个数字是数字或其他字符,并从中提取浮点数,但事实是如果您遇到此错误,则表明您没有完全理解字符串的结构。始终只使用最后两个字符可能不安全。不要只是对问题进行处理,请确保您了解其来源。更具原则性的方法可能是使用正则表达式。
RA = np.array(['cwp+17', 'cn95', 'awd+12', 'aw+7a'])
RA = [re.findall(r'\d+|$', x)[0] for x in RA]
RA = np.asarray(RA).astype(np.float)
print(RA)

out:
[17. 95. 12.  7.]