Debian Codegraph @

petl/transform/unpacks.py

raw
1 from __future__ import absolute_import, print_function, division
2
3
4 import itertools
5 from petl.compat import next, text_type
6
7
8 from petl.errors import ArgumentError
9 from petl.util.base import Table
10
11
12 def unpack(table, field, newfields=None, include_original=False, missing=None):
13 """
14 Unpack data values that are lists or tuples. E.g.::
15
16 >>> import petl as etl
17 >>> table1 = [['foo', 'bar'],
18 ... [1, ['a', 'b']],
19 ... [2, ['c', 'd']],
20 ... [3, ['e', 'f']]]
21 >>> table2 = etl.unpack(table1, 'bar', ['baz', 'quux'])
22 >>> table2
23 +-----+-----+------+
24 | foo | baz | quux |
25 +=====+=====+======+
26 | 1 | 'a' | 'b' |
27 +-----+-----+------+
28 | 2 | 'c' | 'd' |
29 +-----+-----+------+
30 | 3 | 'e' | 'f' |
31 +-----+-----+------+
32
33 This function will attempt to unpack exactly the number of values as
34 given by the number of new fields specified. If there are more values
35 than new fields, remaining values will not be unpacked. If there are less
36 values than new fields, `missing` values will be added.
37
38 See also :func:`petl.transform.unpacks.unpackdict`.
39
40 """
41
42 return UnpackView(table, field, newfields=newfields,
43 include_original=include_original, missing=missing)
44
45
46 Table.unpack = unpack
47
48
49 class UnpackView(Table):
50
51 def __init__(self, source, field, newfields=None, include_original=False,
52 missing=None):
53 self.source = source
54 self.field = field
55 self.newfields = newfields
56 self.include_original = include_original
57 self.missing = missing
58
59 def __iter__(self):
60 return iterunpack(self.source, self.field, self.newfields,
61 self.include_original, self.missing)
62
63
64 def iterunpack(source, field, newfields, include_original, missing):
65 it = iter(source)
66
67 try:
68 hdr = next(it)
69 except StopIteration:
70 hdr = []
71 flds = list(map(text_type, hdr))
72 if field in flds:
73 field_index = flds.index(field)
74 elif isinstance(field, int) and field < len(flds):
75 field_index = field
76 field = flds[field_index]
77 else:
78 raise ArgumentError('field invalid: must be either field name or index')
79
80 # determine output fields
81 outhdr = list(flds)
82 if not include_original:
83 outhdr.remove(field)
84 if isinstance(newfields, (list, tuple)):
85 outhdr.extend(newfields)
86 nunpack = len(newfields)
87 elif isinstance(newfields, int):
88 nunpack = newfields
89 newfields = [text_type(field) + text_type(i+1) for i in range(newfields)]
90 outhdr.extend(newfields)
91 elif newfields is None:
92 nunpack = 0
93 else:
94 raise ArgumentError('newfields argument must be list or tuple of field '
95 'names, or int (number of values to unpack)')
96 yield tuple(outhdr)
97
98 # construct the output data
99 for row in it:
100 value = row[field_index]
101 if include_original:
102 out_row = list(row)
103 else:
104 out_row = [v for i, v in enumerate(row) if i != field_index]
105 nvals = len(value)
106 if nunpack > 0:
107 if nvals >= nunpack:
108 newvals = value[:nunpack]
109 else:
110 newvals = list(value) + ([missing] * (nunpack - nvals))
111 out_row.extend(newvals)
112 yield tuple(out_row)
113
114
115 def unpackdict(table, field, keys=None, includeoriginal=False,
116 samplesize=1000, missing=None):
117 """
118 Unpack dictionary values into separate fields. E.g.::
119
120 >>> import petl as etl
121 >>> table1 = [['foo', 'bar'],
122 ... [1, {'baz': 'a', 'quux': 'b'}],
123 ... [2, {'baz': 'c', 'quux': 'd'}],
124 ... [3, {'baz': 'e', 'quux': 'f'}]]
125 >>> table2 = etl.unpackdict(table1, 'bar')
126 >>> table2
127 +-----+-----+------+
128 | foo | baz | quux |
129 +=====+=====+======+
130 | 1 | 'a' | 'b' |
131 +-----+-----+------+
132 | 2 | 'c' | 'd' |
133 +-----+-----+------+
134 | 3 | 'e' | 'f' |
135 +-----+-----+------+
136
137 See also :func:`petl.transform.unpacks.unpack`.
138
139 """
140
141 return UnpackDictView(table, field, keys=keys,
142 includeoriginal=includeoriginal,
143 samplesize=samplesize, missing=missing)
144
145
146 Table.unpackdict = unpackdict
147
148
149 class UnpackDictView(Table):
150
151 def __init__(self, table, field, keys=None, includeoriginal=False,
152 samplesize=1000, missing=None):
153 self.table = table
154 self.field = field
155 self.keys = keys
156 self.includeoriginal = includeoriginal
157 self.samplesize = samplesize
158 self.missing = missing
159
160 def __iter__(self):
161 return iterunpackdict(self.table, self.field, self.keys,
162 self.includeoriginal, self.samplesize,
163 self.missing)
164
165
166 def iterunpackdict(table, field, keys, includeoriginal, samplesize, missing):
167
168 # set up
169 it = iter(table)
170 try:
171 hdr = next(it)
172 except StopIteration:
173 hdr = []
174 flds = list(map(text_type, hdr))
175 fidx = flds.index(field)
176 outhdr = list(flds)
177 if not includeoriginal:
178 del outhdr[fidx]
179
180 # are keys specified?
181 if not keys:
182 # need to sample to find keys
183 sample = list(itertools.islice(it, samplesize))
184 keys = set()
185 for row in sample:
186 try:
187 keys |= set(row[fidx].keys())
188 except AttributeError:
189 pass
190 it = itertools.chain(sample, it)
191 keys = sorted(keys)
192 outhdr.extend(keys)
193 yield tuple(outhdr)
194
195 # generate the data rows
196 for row in it:
197 outrow = list(row)
198 if not includeoriginal:
199 del outrow[fidx]
200 for key in keys:
201 try:
202 outrow.append(row[fidx][key])
203 except (IndexError, KeyError, TypeError):
204 outrow.append(missing)
205 yield tuple(outrow)