Skip to content

Instantly share code, notes, and snippets.

@JoeGermuska
Created April 18, 2012 15:20
Show Gist options
  • Save JoeGermuska/2414297 to your computer and use it in GitHub Desktop.
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
#!/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)
@higs4281
Copy link

nice! and you actually did it in 18, because the close isn't needed when using "with open()"

@JoeGermuska
Copy link
Author

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