[英]how to tell python 3 to skip over non-digit characters from a csv file
I'm using python 3.4.3 我正在使用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? 我对python和堆栈溢出非常陌生,我正在尝试从csv列中计算平均值,一些框包含问号,并且不让我将其转换为float(obv)有谁知道我如何告诉python跳过问题标记还是只是将其删除? 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. 顺便说一句,该代码在其他地方有些奇怪:averageNum是一个不变的对象:将其作为参数传递并在函数内部修改其值不会在其外部进行更改。 If that's what you wanted i suggest you to make your average() function return said average.
如果那是您想要的,我建议您使您的average()函数返回所说的平均值。
You could try something like this 你可以尝试这样的事情
the_numbers = []
for row in reader:
try:
the_numbers.append(float(row[rowNum]))
except:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.