Calculating Number Of Occurrences Of Dual Parameter Match In A Csv Appending The Results To Csv
What I need to do is calculate the following: The number of times a person appears in the list (column 8) on dates prior to the date specified in the row with the same t data in co
Solution 1:
very minor change:
import csv
import datetime
import copy
from collections import defaultdict
with open(r"C:\Temp\test2.csv") as i, open(r"C:\Temp\results2.csv", "wb") as o:
rdr = csv.reader(i)
wrt = csv.writer(o)
# data is a dictionary where we will save current and previous data like:
# {
# (George Smith, 15t): [
# previous date count when column 7 = 1,
# previous date count,
# current date count when column 7 = 1,
# current date count
# ]
data, currdate = defaultdict(lambda:[0, 0, 0, 0]), None
for line in rdr:
date = datetime.datetime.strptime(line[0], '%d/%m/%Y')
# key of dictionary would be tuple looking like
# (George Smith, 15t)
name = (line[7], line[9])
# if date is changed, we have to put current values into previous
# by copying part of the list
#
# (George Smith, 15t): [
# previous date count when column 7 = 1,
# previous date count,
# current date count when column 7 = 1,
# current date count
# ]
#
# becomes
#
# (George Smith, 15t): [
# current date count when column 7 = 1,
# current date count
# current date count when column 7 = 1,
# current date count
# ]
# and then we change currdate variable to current one
if date != currdate or not currdate:
for v in data.itervalues(): v[:2] = v[2:]
currdate = date
# writing current line + first 2 elements from list (previous counts)
wrt.writerow(line + data[name][:2])
# updating current counts
data[name][3] += 1
if line[6] == "1": data[name][2] += 1
Post a Comment for "Calculating Number Of Occurrences Of Dual Parameter Match In A Csv Appending The Results To Csv"