这指的是我以前的问题,它涉及从.asc文件中提取数据并在有多个分隔符的情况下分离它们。
我想对从上述问题生成的列表列表中的浮动元素执行数学操作。但是,已经实现了单个数据与字符串的分离,因为列表列表也以字符串的形式生成了单个元素,我无法对它们执行数学操作。
我希望能够访问列表中的每个元素,将它们转换为浮动类型,然后对它们执行数学操作。

下面是我的代码,在.asc文件中,字符串被分隔成单独的元素,并存储为列表列表。
这是我从更大的列表中得到的一组特定数据的图像。

我从列表中访问特定的数据集,然后当我试图将它们转换为浮动时,我会得到以下错误:ValueError:未能将字符串转换为浮动:'.'
这是我一直在使用的代码
import numpy as np
import pandas as pd
import re
Output_list = []
Final = []
count = 0
with open(r"myfile.asc","r") as file_in:
for line in map(str.strip, file_in):
if "LoggingString :=" in line:
first_quote = line.index('"') # returns the column number where '"' first appears in the
# whole string
last_quote = line.index('"', first_quote + 1) #returns the column value where " appears last
#in the # whole string ( end of line )
Output_list.append(
line[:first_quote].split(maxsplit=1)
+ line[first_quote + 1: last_quote].split(","),
)
Final.append(Output_list[count][8:25])
Data = list(map(float, Output_list[count][8])) #converting column 8th element of every lists
#in Output_list to float
count += 1
df = pd.DataFrame(Output_list)
df.to_csv("Triall_2.csv", sep=';')
df_1 = pd.DataFrame(Final)
df_1.to_csv("Test.csv", sep=";")我也尝试使用np.array(最终)、.astype(浮点)、.tolist()方法,但它没有按我的意愿将字符串更改为浮动。
发布于 2022-11-29 17:19:48
在for-循环外部将Data声明为空列表,并使用.append将浮点数插入其中:
Data = []
with open(r"myfile.asc", "r") as file_in:
for line in map(str.strip, file_in):
if "LoggingString :=" in line:
# ...
Data.append(float(Output_list[count][8]))
count += 1
print(Data)发布于 2022-11-29 13:48:10
当试图将单个字符串'1.06'映射到浮点对象时,会出现此问题。它将将字符串视为数组,并尝试将数组的每个单独元素转换为浮点数对象,但本示例的第二个元素是点字符.,它不能转换为浮点数对象。
>>> my_array = ['0','1.06','23.345']
>>> list(map(float, my_array[1]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '.'相反,更方便地将数组的所有元素转换为浮点对象:
>>> my_array = ['0', '1.06', '23.345']
>>> list(map(float,my_array))
[0.0, 1.06, 23.345]有关更多信息,您可以查看地图文档。
https://stackoverflow.com/questions/74614779
复制相似问题