简体   繁体   中英

how to tell python 3 to skip over non-digit characters from a csv file

I'm using python 3.4.3

I am very new to python and stack overflow, I'm trying to calculate averages from csv columns, some boxes contain question marks and wont let me convert them to float (obv) does anyone know how I can tell python to skip over the question marks or just remove them? Any feedback would be much help thanks.

average0 = 0
average1 = 0
average2 = 0
def average(rowNum, averageNum):
    with open('positive.csv', newline='') as f:
        reader = csv.reader(f)
        the_numbers = [float(row[rowNum]) for row in reader]
        averageNum = sum(the_numbers) / len(the_numbers)
        averageWith.insert(rowNum, averageNum)
def main():
    average(0, average0)
    average(1, average1)
    average(2, average2)
main()

if the strange characters are known (ie only '?') perhaps something like this?

    the_numbers = [float(row[rowNum]) for row in reader if row[rowNum] not in "?"] 
    #replace "?" with a string of any strange characters

BTW, that code has something weird somewhere else: averageNum is an inmutable object: passing it as an argument and modifying its value inside the function won't change it outside of it. If that's what you wanted i suggest you to make your average() function return said average.

You could try something like this

the_numbers = []
for row in reader:
  try:
    the_numbers.append(float(row[rowNum]))
  except:
    pass

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