简体   繁体   中英

Find the average in a csv file with python (ignore null)

I have a csv file read with python and I need to find the average for each row and put it in a list. The problem is the average should be found ignoring null values for each row. To be precise, the length of the row should ignore null entries. In the example below, the average of A is 7 and B should be 67.3

csv file

the python standard csv library should work here.

It returns a list of rows and columns ie [[row0column0, row0column1..], ... [rowNcolumn0, rowNcolumn1]]

I think this code sample should provide a good framework...

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

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

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