Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/thinkbayes2
Path: blob/master/scripts/columns.py
1901 views
1
"""This file contains code related to "Think Bayes",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2014 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
from __future__ import print_function, division
9
10
import csv
11
12
13
def read_csv(filename, constructor):
14
"""Reads a CSV file, returns the header line and a list of objects.
15
16
filename: string filename
17
"""
18
fp = open(filename)
19
reader = csv.reader(fp)
20
21
header = reader.next()
22
names = [s.lower() for s in header]
23
24
objs = [make_object(t, names, constructor) for t in reader]
25
fp.close()
26
27
return objs
28
29
30
def write_csv(filename, header, data):
31
"""Writes a CSV file
32
33
filename: string filename
34
header: list of strings
35
data: list of rows
36
"""
37
fp = open(filename, 'w')
38
writer = csv.writer(fp)
39
writer.writerow(header)
40
41
for t in data:
42
writer.writerow(t)
43
fp.close()
44
45
46
def print_cols(cols):
47
"""Prints the index and first two elements for each column.
48
49
cols: list of columns
50
"""
51
for i, col in enumerate(cols):
52
print(i, col[0], col[1])
53
54
55
def make_col_dict(cols, names):
56
"""Selects columns from a dataset and returns a map from name to column.
57
58
cols: list of columns
59
names: list of names
60
"""
61
col_dict = {}
62
for name, col in zip(names, cols):
63
col_dict[name] = col
64
return col_dict
65
66
67
def make_object(row, names, constructor):
68
"""Turns a row of values into an object.
69
70
row: row of values
71
names: list of attribute names
72
constructor: function that makes the objects
73
74
Returns: new object
75
"""
76
obj = constructor()
77
for name, val in zip(names, row):
78
func = constructor.convert.get(name, int)
79
try:
80
val = func(val)
81
except:
82
pass
83
setattr(obj, name, val)
84
obj.clean()
85
return obj
86
87
88