怎么做'?'等于一个数字,所以当我浏览一个列表时。它将被算作零。(Python)

2024-06-16 12:55:15 发布

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

正如标题所说,我想让它读“?”从excel表格中,当它超过它时,将其计为零。你知道吗

for eachLine in train:
    tempList=eachLine.split(',')
    avg0=float(tempList[0])
    ageL.append(avg0)
    avg1=float(tempList[1])
    sL.append(avg1)
    avg2=float(tempList[2])
    rbsL.append(avg2)
    avg3=float(tempList[3])
    fbsL.append(avg3)
    avg4=float(tempList[4])
    ogtL.append(avg4)
    avg5=float(tempList[5])
    hemo.append(avg5)

我知道这很难看,但对我来说很管用。任何帮助都将不胜感激,谢谢。你知道吗


Tags: in标题forfloatexcel表格appendtemplist
2条回答

如果我了解您想要做什么,您应该创建一个函数来解析每个单元格,并返回一个浮点值或检查问号。你知道吗

def parse_cell(cell):
    try:
        return float(cell)
    except ValueError:
        if cell == "?":
            return 0.0
        raise

然后用这个函数替换每个float调用,即

avg0 = parse_cell(tempList[0])
directory = [ageL, sL, rbsL, fbsL, ogtL, hemo]
for eachLine in train:
    tempList=eachLine.split(',')
    for idx, data in tempList:
        try:
            directory[idx].append(float(data))
        except ValueError:
            directory[idx].append(0.)

相关问题 更多 >