使用python查找csv文件中的平均值(忽略null)

时间:2017-02-23 16:29:25

标签: python

我有一个用python读取的csv文件,我需要找到每行的平均值并将其放在一个列表中。问题是应该找到平均值,忽略每行的${choices[3]})值。确切地说,行的长度应忽略null个条目。在下面的示例中,null的平均值为A7应为B

csv file

1 个答案:

答案 0 :(得分:1)

python标准csv库应该在这里工作。

它返回行和列的列表,即[[row0column0, row0column1..], ... [rowNcolumn0, rowNcolumn1]]

我认为这段代码示例应该提供一个很好的框架......

import csv

columns_to_avg = [1,2] #a list of the indexes of the columns you
                       #   want to avg. In this case, 1 and 2.
with open('example.csv', 'rb') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        #'row' is just a list of column-organized entries
        for i, column in enumerate(row):
            #Check if this column has a value that is not "null"
            #  and if it's a column we want to average!
            if column != "null" and i in columns_to_avg:
                entry_value = float(column) #Convert string to number
                ...
                #Update sum for this column...
                ...
...
#Calculate final averages for each column here
...

https://docs.python.org/2/library/csv.html

修改