简体   繁体   English

如何告诉python 3跳过csv文件中的非数字字符

[英]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.

相关问题 删除Python中第一个非数字之后(包括第一个非数字)的所有非正则表达式的最佳方法 - Best non-regex way to remove all characters after and including the first non-digit in Python 当前面有数字时递归匹配每个非数字字符 - Recursively matching each non-digit characters when preceded by a digit 如何跳过 csv 文件 python 中的非数字行 - how to skip non numeric rows from csv file python 在熊猫数据框中的某些字符之前提取非数字字符 - Extract non-digit characters before certain character in pandas dataframe 如何仅在特定字符串后才匹配数字,如果发现非数字则停止匹配-Python 27 - How to match digits only after a particular string, stop matching if non-digit is found - Python 27 在Python中使用.find查找第一个非数字字符 - Finding first non-digit character with .find in Python 如何将字符串(带有非数字位值分隔符)转换为整数? - How to convert a string (with non-digit place value separators) into an integer? 如何使用神经网络处理数字分类器中的非数字图像 - How to handle non-digit images in digit classifier using neural networks 使用Python从CSV文件中删除非ASCII字符 - remove non ascii characters from csv file using Python python中的正则表达式:匹配两个单词之间的任何非数字字符 - regex in python: match any non-digit character between two words
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM