排除1时计算

2024-09-26 18:09:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常大的文件,由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')

谢谢。如果需要任何澄清,请发表评论。你知道吗


Tags: 文件数据代码元素dataaswithline
3条回答

这应该够了

import csv


def average(L):
    L = [i for i in map(float, L) if i != -1]
    if not L: return None
    return sum(L)/len(L)


with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as fout:
    outfile = csv.writer(fout, delimiter='\t')
    for name, *vals in csv.reader(infile, delimiter='\t'):
        outfile.writerow((name, average(vals))
   data = [float(x) for x in row[1:] if float(x) > -1]
   if data:
      avg = sum(data)/len(data)
   else:
      avg = 0 # or throw an exception; you had a row of all -1's

第一行是相当标准的Pythonism。。。给定一个数组(在本例中为行),您可以通过使用for x in array if条件位迭代列表并过滤掉内容。你知道吗

如果您只想查看最后三个值,根据您所说的最后三个值的含义,您有两个选项:

data = [float(x) for x in row[-3:] if float(x) > -1]

将查看最后3个值,并根据它们是否为-1返回0到3个值。你知道吗

data = [float(x) for x in row[1:] if float(x) > -1][:-3]

将为您提供最多3个最后的“好”值(如果给定行的值为all或几乎all-1,则该值将小于3)

这是和你原来的问题一样的格式。如果行全部为零,则可以编写错误消息,也可以忽略它而不编写任何内容

with open("PSI_Datatxt.txt", 'r') as data:
    for row in data:
        vals = [float(val) for val in row[1:] if float(val) != -1]
        with open("DataEditted","a+") as newdata:
            try:
                newdata.write(str(sum(vals)/len(vals)) + ' ' + '\n')
            except ZeroDivisionError:
                newdata.write("My Error Message Here\n")

相关问题 更多 >

    热门问题