Created
December 24, 2011 16:38
-
-
Save ykarikos/1517740 to your computer and use it in GitHub Desktop.
Count together the CSV rows' last columns and use the first n rows as the key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# Count together the CSV rows' last columns and use the first n rows as the key. | |
# Use cut to crop the key space, e.g. | |
# $ cut -d\; -f 3-4,8 | csvsum.py | |
import sys | |
sums = {} | |
total = 0 | |
for line in sys.stdin: | |
fields = [s.strip('"') for s in line.rstrip().split(";")] | |
try: | |
count = int(fields.pop()) | |
total = total + count | |
key = " ".join(fields) | |
try: | |
sums[key] = sums[key] + count | |
except KeyError: | |
sums[key] = count | |
except ValueError: | |
pass | |
for key in sums.viewkeys(): | |
print key + ": " + str(sums[key]) + " (" + str(sums[key]*100/total) + "%)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment