Python max and min of records with same attributes -
i working list or dictionary gathered csv file. write out new csv file max , min values associated particular attributes, e.g.:
field1 field2 field3 1 hi 1 2 hi 5 3 bye 2 4 bye 7 should listed attribute in field2 in new csv file as:
f1 f2 min max 1 hi 1 5 2 bye 2 7 my info structures pretty weak have attempted couple of different ways including reading csv file. thought there may way find if set info dictionary or list, long can output csv file when find min , max.
here have tried. think it's algorithm issue. bottom code works me not know when not equal anymore not sure when set in csv file min; when list complete?
first attempt:
dict_rows = {} frames = [] lines = (line.strip() line in open(csvfile)) reader = csv.reader(lines, delimiter='\t', quoting=csv.quote_none) = 0 rec in reader: #print rec dict_rows[i] = (rec[1],rec[5]) += 1 ## key in dict_rows[1]: ## if dict_rows[key]>max: ## max = d[key] ## if d[1] == d[1]: ## print d ## print "equal" print dict_rows max_value = max(dict_rows.values()) min_value = min(dict_rows.values()) print max_value print min_value this seemed closer though:
prev_line = none lines = (line.strip() line in open(csvfile)) ## line in lines: ## print prev_line,line ## prev_line = line reader = csv.reader(lines, delimiter='\t', quoting=csv.quote_none) = 1 frames = [] x = bool line in reader: print '%s) %s ' %(i,line) #print 'previous: %s \n current: %s' %(prev_line, line) #print '%s) %s ' %(prev_line,line) ## if == 1: ## print 'first line header' ## next_line = reader.next() if prev_line != none: ## if prev_line[1] != line[1]: ## print '%i) not %s != %s ?' %(i, prev_line[1],line[1]) if prev_line[1] == line[1]: print '%i) equal! %s == %s' %(i, prev_line[1],line[1]) num = line[5] frames.append(num) x = true else: print '%i) not %s != %s ?' %(i, prev_line[1],line[1]) frames = [] x = false prev_line = line if x == true: min_frame = min(frames) max_frame = max(frames) else: min_frame = 0 max_frame = 0 print min_frame print max_frame else: next_line = reader.next() print 'next: %s' % next_line[1] print '%i) %s == %s == %s ?' %(i, prev_line[1],line[1],next_line[1]) if line[1] != next_line[1]: print '%i) %s != %s' %(i, line[1],next_line[1]) elif line[1] != next_line: print '%i) not! %s != %s' %(i, line[1],next_line[1]) +=1
this works:
data={} open(fn) f: reader=csv.reader(f, delimiter='\t', quoting=csv.quote_none) header=next(reader) row in reader: data.setdefault(row[1], []).append(int(row[2])) print 'key\tmin\tmax' k in data.keys(): print '{}\t{}\t{}'.format(k, min(data[k]), max(data[k])) with illustration data, prints:
key min max bye 2 7 hi 1 5 python
No comments:
Post a Comment