简体   繁体   中英

How to make '?' equal a number, so when i go through a list. It will count it as a zero. (Python)

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.

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.

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 ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM