-
Notifications
You must be signed in to change notification settings - Fork 0
/
abs2011_age_sex_pop.py
59 lines (48 loc) · 1.06 KB
/
abs2011_age_sex_pop.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# -*- coding: utf-8 -*-
import csv
fname = 'abs 2011 age sex pop.csv'
fields = [
'code1',
'code2',
'code3',
'code4',
'rollup',
'sa2name',
'Males',
'Females',
'Persons',
'blank1',
'Sex Ratio',
'blank2',
'Median age of Males',
'Median age of Females',
'Median age of Persons',
'blank3',
'People aged 0–14 years',
'People aged 15–64 years',
'People aged 65 years and over']
f = open(fname, 'r')
dr = csv.DictReader(f, fieldnames=fields)
rows = []
codes = {}
for row in dr:
for field in fields[:4]:
if row[field]:
codes[field] = row[field]
if row['sa2name'] and len(codes) == 4:
for field in fields[:4]:
row[field] = codes[field]
row['sa2code'] = ''.join([codes[x] for x in fields[:4]])
new_row = row.copy()
# remove the old codes
[new_row.pop(x) for x in fields[:4]]
# remove blanks
new_row = dict(filter(lambda x: x[1], new_row.items()))
rows.append(new_row)
new_fields = rows[0].keys()
ofname = 'abs2011_age_sex_pop.csv'
of = open(ofname, 'w')
dw = csv.DictWriter(of, new_fields)
dw.writeheader()
dw.writerows(rows)
of.close()