如何在Python中将分割字符串转换为浮点数但忽略对象?
我有一个文本文件 'lines.txt',内容如下:
0.02 7 433 649 239 32
0.04 84 43 594 2 321
0.06 65 34 94 5 138
0.08 43 56 23 10 432
1.00 2 382 37 29 102
1.20 573 475 82 757 29
Time (s)
Number (unit)
Third (none)
Fourth (none)
Fifth (none)
Test (none)
底部的字符串其实是上面数据的列名(从左到右,比如 Time_1 是 0.02
,Number_1 是 7
等等)。我已经用 .split
函数把每一行的字符串分开了。现在我想把底部的6个文本字符串作为列头,给现在分开的浮点数字符串加上列名。
我该怎么写一个函数,把这两部分数据分开,这样我就可以把底部的字符串当作列名来用?
到目前为止,我有:
f = open('lines.txt','r')
lines = f.readlines()
for line in lines:
data = line.split()
data1 = line.strip()
print(data)
for line in data:
if data is not object:
data = [float(x) for x in data]
我觉得这段代码可以把数字形式的数据转换成浮点数,但我无法让它在遇到文本字符串(比如 Time (s))时停止读取。任何帮助都很感激。
3 个回答
0
希望你需要一个数组,第一行是标题,后面的行是数据。
f = open('try.txt','r')
lines = f.readlines()
data={}
cols=[]
# checking each lines and converting all the data to float which is not colomun heading
for index,line in enumerate(lines):
data[index]=[]
for col in line.split():
try:
data[index].append(float(col))
except ValueError:
#if data is not convertable to float add the main line data to cols array
cols.append(line)
break
finalarray = []
for key,value in data.items():
if len(value)==0:
#ignoring the empty dict which represents line for col
continue
else:
#appending lists of float to final array
finalarray.append(value)
#inserting col headings to the index zero
finalarray.insert(0,cols)
#printing final array where line one is col heading and all other lines is rowdata
print(finalarray)
0
如果你知道最后的6行总是你的列名,那么你可以把这个列表分成两部分。
f = open('lines.txt','r')
lines = f.readlines()
columns = lines[-6:]
lines = lines[:-6]
for line in lines:
data = line.split()
data1 = line.strip()
print(data)...
使用 columns
来给你的列命名。
2
如果你无法转换这行内容,可以把它保存为标题:
with open('lines.txt') as file:
data = []
headings = []
for line in file:
try:
data.append([float(x) for x in line.split()])
except ValueError:
headings.append(line.strip())
print(headings)
for line in data:
print(line)
输出结果:
['Time (s)', 'Number (unit)', 'Third (none)', 'Fourth (none)', 'Fifth (none)', 'Test (none)']
[0.02, 7.0, 433.0, 649.0, 239.0, 32.0]
[0.04, 84.0, 43.0, 594.0, 2.0, 321.0]
[0.06, 65.0, 34.0, 94.0, 5.0, 138.0]
[0.08, 43.0, 56.0, 23.0, 10.0, 432.0]
[1.0, 2.0, 382.0, 37.0, 29.0, 102.0]
[1.2, 573.0, 475.0, 82.0, 757.0, 29.0]
要写入一个CSV文件,可以添加:
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(headings)
writer.writerows(data)
output.csv:
Time (s),Number (unit),Third (none),Fourth (none),Fifth (none),Test (none)
0.02,7.0,433.0,649.0,239.0,32.0
0.04,84.0,43.0,594.0,2.0,321.0
0.06,65.0,34.0,94.0,5.0,138.0
0.08,43.0,56.0,23.0,10.0,432.0
1.0,2.0,382.0,37.0,29.0,102.0
1.2,573.0,475.0,82.0,757.0,29.0