Home > database >  Python- Convert string which have numbers and letters to float for np.list
Python- Convert string which have numbers and letters to float for np.list

Time:11-22

I have a text that I use for taking data. I want to take this "line" and make it numpy list. My data is string but it has numbers and E letters. Because of this I can't convert it to float and taking it to list.

import numpy as np
import re 


with open("FEMMeshGmsh.inp", "r") as file:  

     for line in file.readlines():
       if " " in line:
           line = line[:-1]
           
           a = np.array(line)
           print(a)
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
152,1,0.0000000000000E 00
153,1,0.0000000000000E 00
154,1,0.0000000000000E 00
155,1,6.2500000000000E 01
156,1,6.2500000000000E 01
157,1,6.2500000000000E 01
158,1,6.2500000000000E 01
159,1,0.0000000000000E 00
160,1,0.0000000000000E 00
161,1,0.0000000000000E 00
162,1,6.2500000000000E 01
163,1,6.2500000000000E 01
164,1,6.2500000000000E 01
165,1,6.2500000000000E 01
166,1,6.2500000000000E 01
424,1,1.2500000000000E 02
425,1,1.2500000000000E 02
426,1,1.2500000000000E 02
427,1,1.2500000000000E 02
428,1,1.2500000000000E 02
429,1,1.2500000000000E 02
430,1,1.2500000000000E 02

I tried this code but the output is not in the list. I tried to convert this string to float using astype. But I took ValueError: could not convert string to float: '10,1,0.0000000000000E 00' this error.

CodePudding user response:

You can do that :

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)

CodePudding user response:

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()

Just split the lines on the comma; conversion to floats is easy from that:

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]])

Or just using list and 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
  • Related