Debian Codegraph @

petl/transform/selects.py

raw
1 from __future__ import absolute_import, print_function, division
2
3
4 import operator
5 from petl.compat import next, string_types, callable, text_type
6 from petl.comparison import Comparable
7
8
9 from petl.errors import ArgumentError
10 from petl.util.base import asindices, expr, Table, values, Record
11
12
13 def select(table, *args, **kwargs):
14 """
15 Select rows meeting a condition. E.g.::
16
17 >>> import petl as etl
18 >>> table1 = [['foo', 'bar', 'baz'],
19 ... ['a', 4, 9.3],
20 ... ['a', 2, 88.2],
21 ... ['b', 1, 23.3],
22 ... ['c', 8, 42.0],
23 ... ['d', 7, 100.9],
24 ... ['c', 2]]
25 >>> # the second positional argument can be a function accepting
26 ... # a row
27 ... table2 = etl.select(table1,
28 ... lambda rec: rec.foo == 'a' and rec.baz > 88.1)
29 >>> table2
30 +-----+-----+------+
31 | foo | bar | baz |
32 +=====+=====+======+
33 | 'a' | 2 | 88.2 |
34 +-----+-----+------+
35
36 >>> # the second positional argument can also be an expression
37 ... # string, which will be converted to a function using petl.expr()
38 ... table3 = etl.select(table1, "{foo} == 'a' and {baz} > 88.1")
39 >>> table3
40 +-----+-----+------+
41 | foo | bar | baz |
42 +=====+=====+======+
43 | 'a' | 2 | 88.2 |
44 +-----+-----+------+
45
46 >>> # the condition can also be applied to a single field
47 ... table4 = etl.select(table1, 'foo', lambda v: v == 'a')
48 >>> table4
49 +-----+-----+------+
50 | foo | bar | baz |
51 +=====+=====+======+
52 | 'a' | 4 | 9.3 |
53 +-----+-----+------+
54 | 'a' | 2 | 88.2 |
55 +-----+-----+------+
56
57 The complement of the selection can be returned (i.e., the query can be
58 inverted) by providing `complement=True` as a keyword argument.
59
60 The ``trusted`` keyword argument can be used to specify whether the
61 expression is trusted. See `:func:`petl.util.base.expr` for details.
62
63 """
64
65 missing = kwargs.get('missing', None)
66 complement = kwargs.get('complement', False)
67 trusted = kwargs.get('trusted', True)
68
69 if len(args) == 0:
70 raise ArgumentError('missing positional argument')
71 elif len(args) == 1:
72 where = args[0]
73 if isinstance(where, string_types):
74 where = expr(where, trusted=trusted)
75 else:
76 assert callable(where), 'second argument must be string or callable'
77 return RowSelectView(table, where, missing=missing,
78 complement=complement)
79 else:
80 field = args[0]
81 where = args[1]
82 assert callable(where), 'third argument must be callable'
83 return FieldSelectView(table, field, where, complement=complement,
84 missing=missing)
85
86
87 Table.select = select
88
89
90 class RowSelectView(Table):
91
92 def __init__(self, source, where, missing=None, complement=False):
93 self.source = source
94 self.where = where
95 self.missing = missing
96 self.complement = complement
97
98 def __iter__(self):
99 return iterrowselect(self.source, self.where, self.missing,
100 self.complement)
101
102
103 class FieldSelectView(Table):
104
105 def __init__(self, source, field, where, complement=False, missing=None):
106 self.source = source
107 self.field = field
108 self.where = where
109 self.complement = complement
110 self.missing = missing
111
112 def __iter__(self):
113 return iterfieldselect(self.source, self.field, self.where,
114 self.complement, self.missing)
115
116
117 def iterfieldselect(source, field, where, complement, missing):
118 it = iter(source)
119 try:
120 hdr = next(it)
121 yield tuple(hdr)
122 except StopIteration:
123 hdr = [] # will raise FieldSelectionError below
124 indices = asindices(hdr, field)
125 getv = operator.itemgetter(*indices)
126 for row in it:
127 try:
128 v = getv(row)
129 except IndexError:
130 v = missing
131 if bool(where(v)) != complement: # XOR
132 yield tuple(row)
133
134
135 def iterrowselect(source, where, missing, complement):
136 it = iter(source)
137 try:
138 hdr = next(it)
139 except StopIteration:
140 return # will yield nothing
141 flds = list(map(text_type, hdr))
142 yield tuple(hdr)
143 it = (Record(row, flds, missing=missing) for row in it)
144 for row in it:
145 if bool(where(row)) != complement: # XOR
146 yield tuple(row) # need to convert back to tuple?
147
148
149 def rowlenselect(table, n, complement=False):
150 """Select rows of length `n`."""
151
152 where = lambda row: len(row) == n
153 return select(table, where, complement=complement)
154
155
156 Table.rowlenselect = rowlenselect
157
158
159 def selectop(table, field, value, op, complement=False):
160 """Select rows where the function `op` applied to the given field and
161 the given value returns `True`."""
162
163 return select(table, field, lambda v: op(v, value),
164 complement=complement)
165
166
167 Table.selectop = selectop
168
169
170 def selecteq(table, field, value, complement=False):
171 """Select rows where the given field equals the given value."""
172
173 return selectop(table, field, value, operator.eq, complement=complement)
174
175
176 Table.selecteq = selecteq
177 Table.eq = selecteq
178
179
180 def selectne(table, field, value, complement=False):
181 """Select rows where the given field does not equal the given value."""
182
183 return selectop(table, field, value, operator.ne, complement=complement)
184
185
186 Table.selectne = selectne
187 Table.ne = selectne
188
189
190 def selectlt(table, field, value, complement=False):
191 """Select rows where the given field is less than the given value."""
192
193 value = Comparable(value)
194 return selectop(table, field, value, operator.lt, complement=complement)
195
196
197 Table.selectlt = selectlt
198 Table.lt = selectlt
199
200
201 def selectle(table, field, value, complement=False):
202 """Select rows where the given field is less than or equal to the given
203 value."""
204
205 value = Comparable(value)
206 return selectop(table, field, value, operator.le, complement=complement)
207
208
209 Table.selectle = selectle
210 Table.le = selectle
211
212
213 def selectgt(table, field, value, complement=False):
214 """Select rows where the given field is greater than the given value."""
215
216 value = Comparable(value)
217 return selectop(table, field, value, operator.gt, complement=complement)
218
219
220 Table.selectgt = selectgt
221 Table.gt = selectgt
222
223
224 def selectge(table, field, value, complement=False):
225 """Select rows where the given field is greater than or equal to the given
226 value."""
227
228 value = Comparable(value)
229 return selectop(table, field, value, operator.ge, complement=complement)
230
231
232 Table.selectge = selectge
233 Table.ge = selectge
234
235
236 def selectcontains(table, field, value, complement=False):
237 """Select rows where the given field contains the given value."""
238
239 return selectop(table, field, value, operator.contains,
240 complement=complement)
241
242
243 Table.selectcontains = selectcontains
244
245
246 def selectin(table, field, value, complement=False):
247 """Select rows where the given field is a member of the given value."""
248
249 return select(table, field, lambda v: v in value,
250 complement=complement)
251
252
253 Table.selectin = selectin
254
255
256 def selectnotin(table, field, value, complement=False):
257 """Select rows where the given field is not a member of the given value."""
258
259 return select(table, field, lambda v: v not in value,
260 complement=complement)
261
262
263 Table.selectnotin = selectnotin
264
265
266 def selectis(table, field, value, complement=False):
267 """Select rows where the given field `is` the given value."""
268
269 return selectop(table, field, value, operator.is_, complement=complement)
270
271
272 Table.selectis = selectis
273
274
275 def selectisnot(table, field, value, complement=False):
276 """Select rows where the given field `is not` the given value."""
277
278 return selectop(table, field, value, operator.is_not, complement=complement)
279
280
281 Table.selectisnot = selectisnot
282
283
284 def selectisinstance(table, field, value, complement=False):
285 """Select rows where the given field is an instance of the given type."""
286
287 return selectop(table, field, value, isinstance, complement=complement)
288
289
290 Table.selectisinstance = selectisinstance
291
292
293 def selectrangeopenleft(table, field, minv, maxv, complement=False):
294 """Select rows where the given field is greater than or equal to `minv` and
295 less than `maxv`."""
296
297 minv = Comparable(minv)
298 maxv = Comparable(maxv)
299 return select(table, field, lambda v: minv <= v < maxv,
300 complement=complement)
301
302
303 Table.selectrangeopenleft = selectrangeopenleft
304
305
306 def selectrangeopenright(table, field, minv, maxv, complement=False):
307 """Select rows where the given field is greater than `minv` and
308 less than or equal to `maxv`."""
309
310 minv = Comparable(minv)
311 maxv = Comparable(maxv)
312 return select(table, field, lambda v: minv < v <= maxv,
313 complement=complement)
314
315
316 Table.selectrangeopenright = selectrangeopenright
317
318
319 def selectrangeopen(table, field, minv, maxv, complement=False):
320 """Select rows where the given field is greater than or equal to `minv` and
321 less than or equal to `maxv`."""
322
323 minv = Comparable(minv)
324 maxv = Comparable(maxv)
325 return select(table, field, lambda v: minv <= v <= maxv,
326 complement=complement)
327
328
329 Table.selectrangeopen = selectrangeopen
330
331
332 def selectrangeclosed(table, field, minv, maxv, complement=False):
333 """Select rows where the given field is greater than `minv` and
334 less than `maxv`."""
335
336 minv = Comparable(minv)
337 maxv = Comparable(maxv)
338 return select(table, field, lambda v: minv < Comparable(v) < maxv,
339 complement=complement)
340
341
342 Table.selectrangeclosed = selectrangeclosed
343
344
345 def selecttrue(table, field, complement=False):
346 """Select rows where the given field evaluates `True`."""
347
348 return select(table, field, lambda v: bool(v), complement=complement)
349
350
351 Table.selecttrue = selecttrue
352 Table.true = selecttrue
353
354
355 def selectfalse(table, field, complement=False):
356 """Select rows where the given field evaluates `False`."""
357
358 return select(table, field, lambda v: not bool(v),
359 complement=complement)
360
361
362 Table.selectfalse = selectfalse
363 Table.false = selectfalse
364
365
366 def selectnone(table, field, complement=False):
367 """Select rows where the given field is `None`."""
368
369 return select(table, field, lambda v: v is None, complement=complement)
370
371
372 Table.selectnone = selectnone
373 Table.none = selectnone
374
375
376 def selectnotnone(table, field, complement=False):
377 """Select rows where the given field is not `None`."""
378
379 return select(table, field, lambda v: v is not None,
380 complement=complement)
381
382
383 Table.selectnotnone = selectnotnone
384 Table.notnone = selectnotnone
385
386
387 def selectusingcontext(table, query):
388 """
389 Select rows based on data in the current row and/or previous and
390 next row. E.g.::
391
392 >>> import petl as etl
393 >>> table1 = [['foo', 'bar'],
394 ... ['A', 1],
395 ... ['B', 4],
396 ... ['C', 5],
397 ... ['D', 9]]
398 >>> def query(prv, cur, nxt):
399 ... return ((prv is not None and (cur.bar - prv.bar) < 2)
400 ... or (nxt is not None and (nxt.bar - cur.bar) < 2))
401 ...
402 >>> table2 = etl.selectusingcontext(table1, query)
403 >>> table2
404 +-----+-----+
405 | foo | bar |
406 +=====+=====+
407 | 'B' | 4 |
408 +-----+-----+
409 | 'C' | 5 |
410 +-----+-----+
411
412 The `query` function should accept three rows and return a boolean value.
413
414 """
415
416 return SelectUsingContextView(table, query)
417
418
419 Table.selectusingcontext = selectusingcontext
420
421
422 class SelectUsingContextView(Table):
423
424 def __init__(self, table, query):
425 self.table = table
426 self.query = query
427
428 def __iter__(self):
429 return iterselectusingcontext(self.table, self.query)
430
431
432 def iterselectusingcontext(table, query):
433 it = iter(table)
434 try:
435 hdr = tuple(next(it))
436 except StopIteration:
437 return # will yield nothing
438 flds = list(map(text_type, hdr))
439 yield hdr
440 it = (Record(row, flds) for row in it)
441 prv = None
442 cur = next(it)
443 for nxt in it:
444 if query(prv, cur, nxt):
445 yield cur
446 prv = cur
447 cur = nxt
448 # handle last row
449 if query(prv, cur, None):
450 yield cur
451
452
453 def facet(table, key):
454 """
455 Return a dictionary mapping field values to tables. E.g.::
456
457 >>> import petl as etl
458 >>> table1 = [['foo', 'bar', 'baz'],
459 ... ['a', 4, 9.3],
460 ... ['a', 2, 88.2],
461 ... ['b', 1, 23.3],
462 ... ['c', 8, 42.0],
463 ... ['d', 7, 100.9],
464 ... ['c', 2]]
465 >>> foo = etl.facet(table1, 'foo')
466 >>> sorted(foo.keys())
467 ['a', 'b', 'c', 'd']
468 >>> foo['a']
469 +-----+-----+------+
470 | foo | bar | baz |
471 +=====+=====+======+
472 | 'a' | 4 | 9.3 |
473 +-----+-----+------+
474 | 'a' | 2 | 88.2 |
475 +-----+-----+------+
476
477 >>> foo['c']
478 +-----+-----+------+
479 | foo | bar | baz |
480 +=====+=====+======+
481 | 'c' | 8 | 42.0 |
482 +-----+-----+------+
483 | 'c' | 2 | |
484 +-----+-----+------+
485
486 >>> # works with compound keys too
487 >>> table2 = [['foo', 'bar', 'baz'],
488 ... ['a', 1, True],
489 ... ['b', 2, False],
490 ... ['b', 3, True],
491 ... ['b', 3, False]]
492 >>> foobar = etl.facet(table2, ('foo', 'bar'))
493
494 >>> sorted(foobar.keys())
495 [('a', 1), ('b', 2), ('b', 3)]
496
497 >>> foobar[('b', 3)]
498 +-----+-----+-------+
499 | foo | bar | baz |
500 +=====+=====+=======+
501 | 'b' | 3 | True |
502 +-----+-----+-------+
503 | 'b' | 3 | False |
504 +-----+-----+-------+
505
506 See also :func:`petl.util.materialise.facetcolumns`.
507
508 """
509
510 fct = dict()
511 for v in set(values(table, key)):
512 fct[v] = selecteq(table, key, v)
513 return fct
514
515
516 Table.facet = facet
517
518
519 def biselect(table, *args, **kwargs):
520 """Return two tables, the first containing selected rows, the second
521 containing remaining rows. E.g.::
522
523 >>> import petl as etl
524 >>> table1 = [['foo', 'bar', 'baz'],
525 ... ['a', 4, 9.3],
526 ... ['a', 2, 88.2],
527 ... ['b', 1, 23.3],
528 ... ['c', 8, 42.0],
529 ... ['d', 7, 100.9],
530 ... ['c', 2]]
531 >>> table2, table3 = etl.biselect(table1, lambda rec: rec.foo == 'a')
532 >>> table2
533 +-----+-----+------+
534 | foo | bar | baz |
535 +=====+=====+======+
536 | 'a' | 4 | 9.3 |
537 +-----+-----+------+
538 | 'a' | 2 | 88.2 |
539 +-----+-----+------+
540 >>> table3
541 +-----+-----+-------+
542 | foo | bar | baz |
543 +=====+=====+=======+
544 | 'b' | 1 | 23.3 |
545 +-----+-----+-------+
546 | 'c' | 8 | 42.0 |
547 +-----+-----+-------+
548 | 'd' | 7 | 100.9 |
549 +-----+-----+-------+
550 | 'c' | 2 | |
551 +-----+-----+-------+
552
553 .. versionadded:: 1.1.0
554
555 """
556
557 # override complement kwarg
558 kwargs['complement'] = False
559 t1 = select(table, *args, **kwargs)
560 kwargs['complement'] = True
561 t2 = select(table, *args, **kwargs)
562 return t1, t2
563
564
565 Table.biselect = biselect