numpy Python-将包含数字和字母的字符串转换为np.list的浮点数

sd2nnvve  于 2022-11-23  发布在  Python
关注(0)|答案(2)|浏览(145)

我有一个文本,我用来获取数据。我想把这个“行”,使它numpy列表。我的数据是字符串,但它有数字和E字母。因为这我不能把它转换为浮点数,并把它的列表。
第一个
我尝试了这段代码,但输出不在列表中。我尝试使用a类型将此字符串转换为float。但我使用了ValueError:无法将字符串转换为浮点数:'10,1,0.00000000000E +00'此错误

42fyovps

42fyovps1#

您可以这样做:

import numpy as np
import re 

with open("FEMMeshGmsh.inp", "r") as file:  
     for line in file.readlines():
       if "+" in line:
           line = line[:-1]
           line_array = line.split(",")
           number_array = line_array[-1].split("E+") 
           line_array[-1] = float(number_array[0]) * 10 ** int(number_array[1])
           a = np.array(line_array)
           print(a)
cbwuti44

cbwuti442#

In [757]: lines="""10,1,0.0000000000000E+00
     ...: 11,1,0.0000000000000E+00
     ...: 26,1,0.0000000000000E+00
     ...: 27,1,0.0000000000000E+00
     ...: 80,1,6.2500000000000E+01""".splitlines()

就在逗号上拆分行;转换为浮点数很容易,因为:

In [758]: lines1 = [l.split(',') for l in lines]

In [759]: lines1
Out[759]: 
[['10', '1', '0.0000000000000E+00'],
 ['11', '1', '0.0000000000000E+00'],
 ['26', '1', '0.0000000000000E+00'],
 ['27', '1', '0.0000000000000E+00'],
 ['80', '1', '6.2500000000000E+01']]

In [760]: arr = np.array(lines1,float)

In [761]: arr
Out[761]: 
array([[10. ,  1. ,  0. ],
       [11. ,  1. ,  0. ],
       [26. ,  1. ,  0. ],
       [27. ,  1. ,  0. ],
       [80. ,  1. , 62.5]])

或者只使用list和float

In [762]: lines[0].split(',')
Out[762]: ['10', '1', '0.0000000000000E+00']

In [763]: float(lines[0].split(',')[2])
Out[763]: 0.0

In [764]: float(lines[-1].split(',')[2])
Out[764]: 62.5

相关问题