怎么做的吗?等于一个数字,所以当我浏览一个列表时。它会把它算作0。(Python)

时间:2021-10-20 01:35:04

As the title says, I want it to read the "?" from an excel sheet and count it as a zero when it goes over it.

正如标题所说,我希望它从excel表中读取“?”,并在它经过时将其计数为0。

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)

I know its ugly, but it works for me. Any help would be appreciated, thanks.

我知道它很丑,但它对我有用。如有任何帮助将不胜感激,谢谢。

2 个解决方案

#1


2  

If I understand what you want to do you should create a function to parse each cell and return either a float of the value or check for a question mark.

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

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

Then replace each float call with this function i.e.

然后用这个函数替换每个浮点调用。

avg0 = parse_cell(tempList[0])

#2


-1  

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.)

#1


2  

If I understand what you want to do you should create a function to parse each cell and return either a float of the value or check for a question mark.

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

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

Then replace each float call with this function i.e.

然后用这个函数替换每个浮点调用。

avg0 = parse_cell(tempList[0])

#2


-1  

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.)