Python CSV - Need to Group and Calculate values based on one key -


I have a simple 3 column CSV file for which I use the python for each line group on a line , Then the average value for any other key and return them back to the file is standard CSV format, as has been set;

  id, zip code, rate 1, 19003, 27.50 2, 19003, 31.33 3, 1983, 41.4 4, 1983, 17.95, 102, 102, 21.40   

So what I have to do basically, the average rate for each unique zipcode function [1] in that file is calculated [2] and returns the result . So get the average rate for all records in 19003, 1983, and so on.

I have used the CSV module and have read the file in a dictionary, then on the basis of specific values ​​in the postcode, but no one is able to make progress.

Any help / suggestions appreciated.

I have documented some steps to help clarify things: < Import from import> CSV import from default # a dictionary whose value is the default in a list Data = defaultdict (list) # Open the CSV file and iterate on its rows. The enumerate # function gives us a line line number for i, the line in enumerate (csv.reader (open ('data.csv', 'rb')): # Leave the header line and whichever is empty The rows of the first line are indexed on 0 # i = 0 which is evaluated as a liar, as if there is no empty line, if not, I do not line it: the # columns will be local variables Open _ in, zipcode, level = line # prefix For a zipcode, add level list data [zipcode]. Append (float (level)) # Calculate average of zodod level for loop and statistics on each zipcode and its list of levels .iteritems (): print zipcode, zodiac (level) / float (level (level))

Output:

  19102 21.4 19003 29.415 19083 29.65    

Comments