我有一个非常大的文件,由10000+个值的制表符分隔的值组成。我试图找到数据中每一行的平均值,并将这些新值附加到一个新文件中。但是,未找到的值在大文件中输入为-1。在计算平均值时使用-1值会弄乱我的数据。如何排除这些值? 大文件结构如下所示:
"HsaEX0029886" 100 -1 -1 100 100 100 100 100 100 -1 100 -1 100
"HsaEX0029895" 100 100 91.49 100 100 100 100 100 97.87 95.29 100 100 93.33
"HsaEX0029923" 0 0 0 -1 0 0 0 0 0 9.09 0 5.26 0
在我的代码中,我取最后3个元素,只求3个值的平均值。如果行中最后3个元素是85、12和-1,则需要返回85和12的平均值。以下是我的全部代码:
with open("PSI_Datatxt.txt", 'rt') as data:
next(data)
lis = [line.strip("\n").split("\t") for line in data] # create a list of lists(each row)
for row in lis:
x = float(row[11])
y = float(row[12])
z = float(row[13])
avrg = ((x + y + z) / 3)
with open("DataEditted","a+") as newdata:
if avrg == -1:
continue #skipping lines where all 3 values are -1
else:
newdata.write(str(avrg) + ' ' + '\n')
谢谢。如果需要任何澄清,请发表评论。你知道吗
这应该够了
第一行是相当标准的Pythonism。。。给定一个数组(在本例中为行),您可以通过使用for x in array if条件位迭代列表并过滤掉内容。你知道吗
如果您只想查看最后三个值,根据您所说的最后三个值的含义,您有两个选项:
将查看最后3个值,并根据它们是否为-1返回0到3个值。你知道吗
将为您提供最多3个最后的“好”值(如果给定行的值为all或几乎all-1,则该值将小于3)
这是和你原来的问题一样的格式。如果行全部为零,则可以编写错误消息,也可以忽略它而不编写任何内容
相关问题 更多 >
编程相关推荐