Created
April 18, 2012 15:20
-
-
Save JoeGermuska/2414297 to your computer and use it in GitHub Desktop.
Example of how to convert a csv file to a table of ranked headers for each row
This file contains 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/env python | |
import csv, json | |
from collections import defaultdict | |
r = csv.reader(open("data.csv")) | |
headers = r.next() | |
countries = headers[1:] | |
out_rows = [] | |
for row in r: | |
area = row[0] | |
out_row = [area] | |
values = map(int,row[1:]) | |
d = defaultdict(list) | |
for v,c in zip(values,countries): | |
d[v].append(c) | |
for v in reversed(sorted(d)): | |
if v > 0: | |
if len(d[v]) > 1: | |
out_row.append('[%s]' % (','.join(d[v]))) | |
else: | |
out_row.append(d[v][0]) | |
if len(out_row) < 6: | |
out_row.extend([''] * (6-len(out_row))) | |
out_rows.append(out_row) | |
with open("ranked.json","w") as json_file: | |
json.dump(out_rows,json_file) |
ah right... thanks! updated/adjusted now based on NICAR-L conversation...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice! and you actually did it in 18, because the close isn't needed when using "with open()"