python - Sum of a particular column in a csv file -
there csv file, a.csv
, having content:
place,hotel,food,fare norway,regal,nonveg,5000 poland,jenny,italiano,6000 norway,suzane,vegeterian,4000 norway,regal,nonveg,5000
i have parse csv , obtain output passing arguments in command prompt.
example 1:
mycode.py place
desired output is:
place,fare norway,14000 poland,6000
example 2:
mycode.py place hotel
desired output is:
place,hotel,fare norway,regal,10000 poland,jenny,6000 norway,suzane,4000
so clear above example no matter pass argument gives sum of fare
header common ones.
below code , able pass arguments , output, stuck in sum of fare
. can 1 me this.
import sys import csv import collections d = collections.defaultdict(list) data = [] result = [] final = [] argvs = [] argv_len = len(sys.argv) index = 0 input = '' file = open('a.csv', 'rb') try: reader = csv.reader(file) row in reader: data.append(row) x in range(1, argv_len): argvs.append(sys.argv[x]) argvs.append('fare') input in argvs: y in range(0, len(data[0])): if(input == data[0][y]): z in range(1, len(data)): result.append(data[z][y]) break final.append(result) result = [] new = [] newfinal = [] x in range(0, len(final[0])): y in range(0, len(final)): new.append(final[y][x]) newfinal.append(new) new = [] out = {} in newfinal: out.setdefault(a[0],[]).append(int(a[-1])) open("output.csv", "wb") csv_file: writer = csv.writer(csv_file, dialect='excel', delimiter=',') writer.writerow(argvs) k,v in out.iteritems(): writer.writerow((k,sum(v))) except exception,e: print str(e) finally: file.close()
i edit code , tried group it. able aggregate of fare
not desired output.
so when passing:
mycode.py place hotel
instead of:
place,hotel,fare norway,regal,10000 poland,jenny,6000 norway,suzane,4000
i getting:
place,hotel,fare norway,14000 poland,6000
finally managed desired output.
below sharing final code. \
import sys import csv data = [] result = [] final = [] argvs = [] argv_len = len(sys.argv) index = 0 input = '' file = open('a.csv', 'rb') try: reader = csv.reader(file) row in reader: data.append(row) x in range(1, argv_len): argvs.append(sys.argv[x]) argvs.append('fare') input in argvs: y in range(0, len(data[0])): if(input == data[0][y]): z in range(1, len(data)): result.append(data[z][y]) break final.append(result) result = [] new = [] newfinal = [] x in range(0, len(final[0])): y in range(0, len(final)): new.append(final[y][x]) newfinal.append(new) new = [] out = {} in newfinal: count_val = a[-1] del a[-1] key_val = ','.join(a) out.setdefault(key_val.strip('"'),[]).append(int(count_val)) open("output.csv", "wb") csv_file: writer = csv.writer(csv_file, delimiter=',',quotechar=' ') writer.writerow(argvs) k,v in out.iteritems(): writer.writerow((k,sum(v))) except exception,e: print str(e) finally: file.close()
Comments
Post a Comment