Skip to content

Instantly share code, notes, and snippets.

@stuartathompson
Forked from JoeGermuska/ranker.py
Created April 18, 2012 18:08
Show Gist options
  • Select an option

  • Save stuartathompson/2415494 to your computer and use it in GitHub Desktop.

Select an option

Save stuartathompson/2415494 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
r = csv.reader(open("data.csv"))
headers = r.next()
countries = headers[1:]
with open("ranked.csv","w") as f:
w = csv.writer(f)
w.writerow(['Area','#1','#2','#3','#4','#5'])
for row in r:
area = row[0]
values = map(int,row[1:])
vc = zip(values,countries)
vc.sort()
vc.reverse()
out_row = [area]
vcCount = -1
rowSelect = -1
adjust = 0
once = 0
for value, country in vc:
vcCount = vcCount + 1
rowSelect = rowSelect + 1 - adjust
data = []
if value != 0:
if vcCount-1 != -1:
if value == vc[vcCount-1][0]:
if once == 0:
adjust = adjust + 1
once = 1
out_row[rowSelect] = "[" + out_row[rowSelect].replace('[', '').replace(']','') + ', "' + country + '"]'
else:
adjust = 0
once = 0
out_row.append('"' + country + '"')
else:
out_row.append('"' + country + '"')
if(len(out_row) == 6):
break
w.writerow(out_row)
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment