-
Notifications
You must be signed in to change notification settings - Fork 1
/
lookup.py
165 lines (120 loc) · 4.4 KB
/
lookup.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import io
import os
import numpy as np
import pandas as pd
import requests
import six
import yaml
WORKBENCH_TYPE_LOOKUP = {
"Text": "text",
"Number": "integer"
}
PANDAS_TYPE_LOOKUP = {
"text": str,
"integer": np.int64
}
def render(table, params, *, input_columns):
columns = params["columns"]
keys = params["keys"]
value = params["value"]
version = params["version"] or None
if not columns or not value:
return table
if keys:
keys = keys.split(",")
if len(keys) != len(columns):
return "The number of keys must match the number of columns. (Use commas to separate keys.)"
else:
keys = columns
source = Source()
try:
metadata = source.get_metadata(keys, value, version)
except ValueError:
return "Unable to find lookup table for keys `{}`, value `{}`, and version `{}`".format(
keys, value, version
)
pandas_types = {}
for column, key in zip(columns, keys):
column_type = input_columns[column].type
key_type = WORKBENCH_TYPE_LOOKUP[metadata["columns"][key]["type"]]
if column_type != key_type:
return "Column `{}` has type `{}`. Key `{}` requires type `{}`.".format(
column, column_type, key, key_type
)
pandas_types[key] = PANDAS_TYPE_LOOKUP[key_type]
lookup_table = source.get_table(keys, value, version, column_types=pandas_types)
return table.join(lookup_table, on=keys)
"""
NOTE: Below this point is a port of the original agate-lookup module.
https://github.com/wireservice/agate-lookup
This should really be in it's own module, but Workbench doesn't currently
support that.
"""
def make_table_path(keys, value, version=None):
"""
Generate a path to find a given lookup table.
"""
if isinstance(keys, (list, tuple)):
keys = '/'.join(keys)
path = '%s/%s' % (keys, value)
if version:
path += '.%s' % version
path += '.csv'
return path
def make_metadata_path(keys, value, version=None):
"""
Generate a path to find a given lookup table.
"""
if isinstance(keys, (list, tuple)):
keys = '/'.join(keys)
path = '%s/%s' % (keys, value)
if version:
path += '.%s' % version
path += '.csv.yml'
return path
class Source(object):
"""
A reference to an archive of lookup tables. This is a remote location with
lookup table and metadata files at a known path structure.
:param root:
The root URL to prefix all data and metadata paths.
:param cache:
A path in which to store cached copies of any tables that are used, so
they can continue to be used offline.
"""
def __init__(self, root='http://wireservice.github.io/lookup'):
self._root = root
def get_metadata(self, keys, value, version=None):
"""Fetches metadata related to a specific lookup table.
See :meth:`Source.get_table` for parameter details.
"""
path = make_metadata_path(keys, value, version)
url = '%s/%s' % (self._root, path)
r = requests.get(url)
try:
data = yaml.load(r.text)
except:
raise ValueError('Failed to read or parse YAML at %s' % url)
return data
def get_table(self, keys, value, version=None, column_types=None):
"""Fetches and creates an pandas table from a specified lookup table.
The resulting table will automatically have row names created for the
key columns, thus allowing it to be used as a lookup.
:param keys:
Either a single string or a sequence of keys that identify the
"left side" of the table. For example :code:`'fips'` or
:code:`['city', 'year']`.
:param value:
The value that is being looked up from the given keys. For example
:code:`'state'` or :code:`'population'`.
:param version:
An optional version of the given lookup, if more than one exists.
For instance :code:`'2007'` for the 2007 edition of the NAICS codes
or :code:`'2012'` for the 2012 version.
"""
path = make_table_path(keys, value, version)
url = '%s/%s' % (self._root, path)
r = requests.get(url)
df = pd.read_csv(six.StringIO(r.text), dtype=column_types, index_col=False)
df.set_index(keys, drop=True, inplace=True)
return df