Debian Codegraph @

petl/transform/joins.py

raw
1 from __future__ import absolute_import, division, print_function
2
3 import itertools
4 import operator
5
6 from petl.comparison import Comparable, comparable_itemgetter
7 from petl.compat import next, text_type
8 from petl.errors import ArgumentError
9 from petl.transform.basics import cut, cutout, stack
10 from petl.transform.dedup import distinct
11 from petl.transform.sorts import sort
12 from petl.util.base import Table, asindices, data, header, rowgetter, rowgroupby
13
14
15 def natural_key(left, right):
16 # determine key field or fields
17 lhdr = header(left)
18 lflds = list(map(str, lhdr))
19 rhdr = header(right)
20 rflds = list(map(str, rhdr))
21 key = [f for f in lflds if f in rflds]
22 assert len(key) > 0, 'no fields in common'
23 if len(key) == 1:
24 key = key[0] # deal with singletons
25 return key
26
27
28 def keys_from_args(left, right, key, lkey, rkey):
29
30 if key is lkey is rkey is None:
31 # no keys specified, attempt natural join
32 lkey = rkey = natural_key(left, right)
33 elif key is not None and lkey is rkey is None:
34 # common key specified
35 lkey = rkey = key
36 elif key is None and lkey is not None and rkey is not None:
37 # left and right keys specified
38 pass
39 else:
40 raise ArgumentError(
41 'bad key arguments: either specify key, or specify both lkey and '
42 'rkey, or provide no key/lkey/rkey arguments at all (natural join)'
43 )
44 return lkey, rkey
45
46
47 def join(left, right, key=None, lkey=None, rkey=None, presorted=False,
48 buffersize=None, tempdir=None, cache=True, lprefix=None, rprefix=None):
49 """
50 Perform an equi-join on the given tables. E.g.::
51
52 >>> import petl as etl
53 >>> table1 = [['id', 'colour'],
54 ... [1, 'blue'],
55 ... [2, 'red'],
56 ... [3, 'purple']]
57 >>> table2 = [['id', 'shape'],
58 ... [1, 'circle'],
59 ... [3, 'square'],
60 ... [4, 'ellipse']]
61 >>> table3 = etl.join(table1, table2, key='id')
62 >>> table3
63 +----+----------+----------+
64 | id | colour | shape |
65 +====+==========+==========+
66 | 1 | 'blue' | 'circle' |
67 +----+----------+----------+
68 | 3 | 'purple' | 'square' |
69 +----+----------+----------+
70
71 >>> # if no key is given, a natural join is tried
72 ... table4 = etl.join(table1, table2)
73 >>> table4
74 +----+----------+----------+
75 | id | colour | shape |
76 +====+==========+==========+
77 | 1 | 'blue' | 'circle' |
78 +----+----------+----------+
79 | 3 | 'purple' | 'square' |
80 +----+----------+----------+
81
82 >>> # note behaviour if the key is not unique in either or both tables
83 ... table5 = [['id', 'colour'],
84 ... [1, 'blue'],
85 ... [1, 'red'],
86 ... [2, 'purple']]
87 >>> table6 = [['id', 'shape'],
88 ... [1, 'circle'],
89 ... [1, 'square'],
90 ... [2, 'ellipse']]
91 >>> table7 = etl.join(table5, table6, key='id')
92 >>> table7
93 +----+----------+-----------+
94 | id | colour | shape |
95 +====+==========+===========+
96 | 1 | 'blue' | 'circle' |
97 +----+----------+-----------+
98 | 1 | 'blue' | 'square' |
99 +----+----------+-----------+
100 | 1 | 'red' | 'circle' |
101 +----+----------+-----------+
102 | 1 | 'red' | 'square' |
103 +----+----------+-----------+
104 | 2 | 'purple' | 'ellipse' |
105 +----+----------+-----------+
106
107 >>> # compound keys are supported
108 ... table8 = [['id', 'time', 'height'],
109 ... [1, 1, 12.3],
110 ... [1, 2, 34.5],
111 ... [2, 1, 56.7]]
112 >>> table9 = [['id', 'time', 'weight'],
113 ... [1, 2, 4.5],
114 ... [2, 1, 6.7],
115 ... [2, 2, 8.9]]
116 >>> table10 = etl.join(table8, table9, key=['id', 'time'])
117 >>> table10
118 +----+------+--------+--------+
119 | id | time | height | weight |
120 +====+======+========+========+
121 | 1 | 2 | 34.5 | 4.5 |
122 +----+------+--------+--------+
123 | 2 | 1 | 56.7 | 6.7 |
124 +----+------+--------+--------+
125
126 If `presorted` is True, it is assumed that the data are already sorted by
127 the given key, and the `buffersize`, `tempdir` and `cache` arguments are
128 ignored. Otherwise, the data are sorted, see also the discussion of the
129 `buffersize`, `tempdir` and `cache` arguments under the
130 :func:`petl.transform.sorts.sort` function.
131
132 Left and right tables with different key fields can be handled via the
133 `lkey` and `rkey` arguments.
134
135 .. versionchanged:: 1.7.16
136 To ensure correct results for tables with uneven rows, tables will be
137 squared up before joining to ensure correct results.
138
139 """
140
141 # TODO don't read data twice (occurs if using natural key)
142 lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
143 return JoinView(left, right, lkey=lkey, rkey=rkey,
144 presorted=presorted, buffersize=buffersize, tempdir=tempdir,
145 cache=cache, lprefix=lprefix, rprefix=rprefix)
146
147
148 Table.join = join
149
150
151 class JoinView(Table):
152
153 def __init__(self, left, right, lkey, rkey,
154 presorted=False, leftouter=False, rightouter=False,
155 missing=None, buffersize=None, tempdir=None, cache=True,
156 lprefix=None, rprefix=None):
157 self.lkey = lkey
158 self.rkey = rkey
159 self.left = stack(left, missing=missing)
160 self.right = stack(right, missing=missing)
161 if not presorted:
162 self.left = sort(self.left, lkey, buffersize=buffersize,
163 tempdir=tempdir, cache=cache)
164 self.right = sort(self.right, rkey, buffersize=buffersize,
165 tempdir=tempdir, cache=cache)
166 self.leftouter = leftouter
167 self.rightouter = rightouter
168 self.missing = missing
169 self.lprefix = lprefix
170 self.rprefix = rprefix
171
172 def __iter__(self):
173 return iterjoin(self.left, self.right, self.lkey, self.rkey,
174 leftouter=self.leftouter, rightouter=self.rightouter,
175 missing=self.missing, lprefix=self.lprefix,
176 rprefix=self.rprefix)
177
178
179 def leftjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
180 presorted=False, buffersize=None, tempdir=None, cache=True,
181 lprefix=None, rprefix=None):
182 """
183 Perform a left outer join on the given tables. E.g.::
184
185 >>> import petl as etl
186 >>> table1 = [['id', 'colour'],
187 ... [1, 'blue'],
188 ... [2, 'red'],
189 ... [3, 'purple']]
190 >>> table2 = [['id', 'shape'],
191 ... [1, 'circle'],
192 ... [3, 'square'],
193 ... [4, 'ellipse']]
194 >>> table3 = etl.leftjoin(table1, table2, key='id')
195 >>> table3
196 +----+----------+----------+
197 | id | colour | shape |
198 +====+==========+==========+
199 | 1 | 'blue' | 'circle' |
200 +----+----------+----------+
201 | 2 | 'red' | None |
202 +----+----------+----------+
203 | 3 | 'purple' | 'square' |
204 +----+----------+----------+
205
206 If `presorted` is True, it is assumed that the data are already sorted by
207 the given key, and the `buffersize`, `tempdir` and `cache` arguments are
208 ignored. Otherwise, the data are sorted, see also the discussion of the
209 `buffersize`, `tempdir` and `cache` arguments under the
210 :func:`petl.transform.sorts.sort` function.
211
212 Left and right tables with different key fields can be handled via the
213 `lkey` and `rkey` arguments.
214
215 .. versionchanged:: 1.7.16
216 To ensure correct results for tables with uneven rows, tables will be
217 squared up before joining to ensure correct results.
218
219 """
220
221 # TODO don't read data twice (occurs if using natural key)
222 lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
223 return JoinView(left, right, lkey=lkey, rkey=rkey,
224 presorted=presorted, leftouter=True, rightouter=False,
225 missing=missing, buffersize=buffersize, tempdir=tempdir,
226 cache=cache, lprefix=lprefix, rprefix=rprefix)
227
228
229 Table.leftjoin = leftjoin
230
231
232 def rightjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
233 presorted=False, buffersize=None, tempdir=None, cache=True,
234 lprefix=None, rprefix=None):
235 """
236 Perform a right outer join on the given tables. E.g.::
237
238 >>> import petl as etl
239 >>> table1 = [['id', 'colour'],
240 ... [1, 'blue'],
241 ... [2, 'red'],
242 ... [3, 'purple']]
243 >>> table2 = [['id', 'shape'],
244 ... [1, 'circle'],
245 ... [3, 'square'],
246 ... [4, 'ellipse']]
247 >>> table3 = etl.rightjoin(table1, table2, key='id')
248 >>> table3
249 +----+----------+-----------+
250 | id | colour | shape |
251 +====+==========+===========+
252 | 1 | 'blue' | 'circle' |
253 +----+----------+-----------+
254 | 3 | 'purple' | 'square' |
255 +----+----------+-----------+
256 | 4 | None | 'ellipse' |
257 +----+----------+-----------+
258
259 If `presorted` is True, it is assumed that the data are already sorted by
260 the given key, and the `buffersize`, `tempdir` and `cache` arguments are
261 ignored. Otherwise, the data are sorted, see also the discussion of the
262 `buffersize`, `tempdir` and `cache` arguments under the
263 :func:`petl.transform.sorts.sort` function.
264
265 Left and right tables with different key fields can be handled via the
266 `lkey` and `rkey` arguments.
267
268 .. versionchanged:: 1.7.16
269 To ensure correct results for tables with uneven rows, tables will be
270 squared up before joining to ensure correct results.
271
272 """
273
274 # TODO don't read data twice (occurs if using natural key)
275 lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
276 return JoinView(left, right, lkey=lkey, rkey=rkey,
277 presorted=presorted, leftouter=False, rightouter=True,
278 missing=missing, buffersize=buffersize,
279 tempdir=tempdir, cache=cache, lprefix=lprefix,
280 rprefix=rprefix)
281
282
283 Table.rightjoin = rightjoin
284
285
286 def outerjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
287 presorted=False, buffersize=None, tempdir=None, cache=True,
288 lprefix=None, rprefix=None):
289 """
290 Perform a full outer join on the given tables. E.g.::
291
292 >>> import petl as etl
293 >>> table1 = [['id', 'colour'],
294 ... [1, 'blue'],
295 ... [2, 'red'],
296 ... [3, 'purple']]
297 >>> table2 = [['id', 'shape'],
298 ... [1, 'circle'],
299 ... [3, 'square'],
300 ... [4, 'ellipse']]
301 >>> table3 = etl.outerjoin(table1, table2, key='id')
302 >>> table3
303 +----+----------+-----------+
304 | id | colour | shape |
305 +====+==========+===========+
306 | 1 | 'blue' | 'circle' |
307 +----+----------+-----------+
308 | 2 | 'red' | None |
309 +----+----------+-----------+
310 | 3 | 'purple' | 'square' |
311 +----+----------+-----------+
312 | 4 | None | 'ellipse' |
313 +----+----------+-----------+
314
315 If `presorted` is True, it is assumed that the data are already sorted by
316 the given key, and the `buffersize`, `tempdir` and `cache` arguments are
317 ignored. Otherwise, the data are sorted, see also the discussion of the
318 `buffersize`, `tempdir` and `cache` arguments under the
319 :func:`petl.transform.sorts.sort` function.
320
321 Left and right tables with different key fields can be handled via the
322 `lkey` and `rkey` arguments.
323
324 .. versionchanged:: 1.7.16
325 To ensure correct results for tables with uneven rows, tables will be
326 squared up before joining to ensure correct results.
327
328 """
329
330 # TODO don't read data twice (occurs if using natural key)
331 lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
332 return JoinView(left, right, lkey=lkey, rkey=rkey,
333 presorted=presorted, leftouter=True, rightouter=True,
334 missing=missing, buffersize=buffersize, tempdir=tempdir,
335 cache=cache, lprefix=lprefix, rprefix=rprefix)
336
337
338 Table.outerjoin = outerjoin
339
340
341 def iterjoin(left, right, lkey, rkey, leftouter=False, rightouter=False,
342 missing=None, lprefix=None, rprefix=None):
343 lit = iter(left)
344 rit = iter(right)
345
346 lhdr = next(lit)
347 rhdr = next(rit)
348
349 # determine indices of the key fields in left and right tables
350 lkind = asindices(lhdr, lkey)
351 rkind = asindices(rhdr, rkey)
352
353 # construct functions to extract key values from both tables
354 lgetk = comparable_itemgetter(*lkind)
355 rgetk = comparable_itemgetter(*rkind)
356
357 # determine indices of non-key fields in the right table
358 # (in the output, we only include key fields from the left table - we
359 # don't want to duplicate fields)
360 rvind = [i for i in range(len(rhdr)) if i not in rkind]
361 rgetv = rowgetter(*rvind)
362
363 # determine the output fields
364 if lprefix is None:
365 outhdr = list(lhdr)
366 else:
367 outhdr = [(text_type(lprefix) + text_type(f)) for f in lhdr]
368 if rprefix is None:
369 outhdr.extend(rgetv(rhdr))
370 else:
371 outhdr.extend([(text_type(rprefix) + text_type(f)) for f in rgetv(rhdr)])
372 yield tuple(outhdr)
373
374 # define a function to join two groups of rows
375 def joinrows(_lrowgrp, _rrowgrp):
376 if _rrowgrp is None:
377 for lrow in _lrowgrp:
378 outrow = list(lrow) # start with the left row
379 # extend with missing values in place of the right row
380 outrow.extend([missing] * len(rvind))
381 yield tuple(outrow)
382 elif _lrowgrp is None:
383 for rrow in _rrowgrp:
384 # start with missing values in place of the left row
385 outrow = [missing] * len(lhdr)
386 # set key values
387 for li, ri in zip(lkind, rkind):
388 outrow[li] = rrow[ri]
389 # extend with non-key values from the right row
390 outrow.extend(rgetv(rrow))
391 yield tuple(outrow)
392 else:
393 _rrowgrp = list(_rrowgrp) # may need to iterate more than once
394 for lrow in _lrowgrp:
395 for rrow in _rrowgrp:
396 # start with the left row
397 outrow = list(lrow)
398 # extend with non-key values from the right row
399 outrow.extend(rgetv(rrow))
400 yield tuple(outrow)
401
402 # construct group iterators for both tables
403 lgit = itertools.groupby(lit, key=lgetk)
404 rgit = itertools.groupby(rit, key=rgetk)
405 lrowgrp = []
406 rrowgrp = []
407
408 # loop until *either* of the iterators is exhausted
409 # initialise here to handle empty tables
410 lkval, rkval = Comparable(None), Comparable(None)
411 try:
412
413 # pick off initial row groups
414 lkval, lrowgrp = next(lgit)
415 rkval, rrowgrp = next(rgit)
416
417 while True:
418 if lkval < rkval:
419 if leftouter:
420 for row in joinrows(lrowgrp, None):
421 yield tuple(row)
422 # advance left
423 lkval, lrowgrp = next(lgit)
424 elif lkval > rkval:
425 if rightouter:
426 for row in joinrows(None, rrowgrp):
427 yield tuple(row)
428 # advance right
429 rkval, rrowgrp = next(rgit)
430 else:
431 for row in joinrows(lrowgrp, rrowgrp):
432 yield tuple(row)
433 # advance both
434 lkval, lrowgrp = next(lgit)
435 rkval, rrowgrp = next(rgit)
436
437 except StopIteration:
438 pass
439
440 # make sure any left rows remaining are yielded
441 if leftouter:
442 if lkval > rkval:
443 # yield anything that got left hanging
444 for row in joinrows(lrowgrp, None):
445 yield tuple(row)
446 # yield the rest
447 for lkval, lrowgrp in lgit:
448 for row in joinrows(lrowgrp, None):
449 yield tuple(row)
450
451 # make sure any right rows remaining are yielded
452 if rightouter:
453 if lkval < rkval:
454 # yield anything that got left hanging
455 for row in joinrows(None, rrowgrp):
456 yield tuple(row)
457 # yield the rest
458 for rkval, rrowgrp in rgit:
459 for row in joinrows(None, rrowgrp):
460 yield tuple(row)
461
462
463 def crossjoin(*tables, **kwargs):
464 """
465 Form the cartesian product of the given tables. E.g.::
466
467 >>> import petl as etl
468 >>> table1 = [['id', 'colour'],
469 ... [1, 'blue'],
470 ... [2, 'red']]
471 >>> table2 = [['id', 'shape'],
472 ... [1, 'circle'],
473 ... [3, 'square']]
474 >>> table3 = etl.crossjoin(table1, table2)
475 >>> table3
476 +----+--------+----+----------+
477 | id | colour | id | shape |
478 +====+========+====+==========+
479 | 1 | 'blue' | 1 | 'circle' |
480 +----+--------+----+----------+
481 | 1 | 'blue' | 3 | 'square' |
482 +----+--------+----+----------+
483 | 2 | 'red' | 1 | 'circle' |
484 +----+--------+----+----------+
485 | 2 | 'red' | 3 | 'square' |
486 +----+--------+----+----------+
487
488 If `prefix` is `True` then field names in the output table header will be
489 prefixed by the index of the input table.
490
491 .. versionchanged:: 1.7.16
492 To ensure correct results for tables with uneven rows, tables will be
493 squared up before joining to ensure correct results.
494
495 """
496
497 return CrossJoinView(*tables, **kwargs)
498
499
500 Table.crossjoin = crossjoin
501
502
503 class CrossJoinView(Table):
504
505 def __init__(self, *sources, **kwargs):
506 self.prefix = kwargs.get('prefix', False)
507 self.missing = kwargs.get('missing', None)
508 self.sources = [stack(source, missing=self.missing) for source in sources]
509
510 def __iter__(self):
511 return itercrossjoin(self.sources, self.prefix)
512
513
514 def itercrossjoin(sources, prefix):
515
516 # construct fields
517 outhdr = list()
518 for i, s in enumerate(sources):
519 if prefix:
520 # use one-based numbering
521 outhdr.extend([text_type(i+1) + '_' + text_type(f) for f in header(s)])
522 else:
523 outhdr.extend(header(s))
524 yield tuple(outhdr)
525
526 datasrcs = [data(src) for src in sources]
527 for prod in itertools.product(*datasrcs):
528 outrow = list()
529 for row in prod:
530 outrow.extend(row)
531 yield tuple(outrow)
532
533
534 def antijoin(left, right, key=None, lkey=None, rkey=None, presorted=False,
535 buffersize=None, tempdir=None, cache=True):
536 """
537 Return rows from the `left` table where the key value does not occur in
538 the `right` table. E.g.::
539
540 >>> import petl as etl
541 >>> table1 = [['id', 'colour'],
542 ... [0, 'black'],
543 ... [1, 'blue'],
544 ... [2, 'red'],
545 ... [4, 'yellow'],
546 ... [5, 'white']]
547 >>> table2 = [['id', 'shape'],
548 ... [1, 'circle'],
549 ... [3, 'square']]
550 >>> table3 = etl.antijoin(table1, table2, key='id')
551 >>> table3
552 +----+----------+
553 | id | colour |
554 +====+==========+
555 | 0 | 'black' |
556 +----+----------+
557 | 2 | 'red' |
558 +----+----------+
559 | 4 | 'yellow' |
560 +----+----------+
561 | 5 | 'white' |
562 +----+----------+
563
564 If `presorted` is True, it is assumed that the data are already sorted by
565 the given key, and the `buffersize`, `tempdir` and `cache` arguments are
566 ignored. Otherwise, the data are sorted, see also the discussion of the
567 `buffersize`, `tempdir` and `cache` arguments under the
568 :func:`petl.transform.sorts.sort` function.
569
570 Left and right tables with different key fields can be handled via the
571 `lkey` and `rkey` arguments.
572
573 """
574
575 lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
576 return AntiJoinView(left=left, right=right, lkey=lkey, rkey=rkey,
577 presorted=presorted, buffersize=buffersize,
578 tempdir=tempdir, cache=cache)
579
580
581 Table.antijoin = antijoin
582
583
584 class AntiJoinView(Table):
585
586 def __init__(self, left, right, lkey, rkey, presorted=False,
587 buffersize=None, tempdir=None, cache=True):
588 if presorted:
589 self.left = left
590 self.right = right
591 else:
592 self.left = sort(left, lkey, buffersize=buffersize,
593 tempdir=tempdir, cache=cache)
594 self.right = sort(right, rkey, buffersize=buffersize,
595 tempdir=tempdir, cache=cache)
596 self.lkey = lkey
597 self.rkey = rkey
598
599 def __iter__(self):
600 return iterantijoin(self.left, self.right, self.lkey, self.rkey)
601
602
603 def iterantijoin(left, right, lkey, rkey):
604 lit = iter(left)
605 rit = iter(right)
606
607 lhdr = next(lit)
608 rhdr = next(rit)
609 yield tuple(lhdr)
610
611 # determine indices of the key fields in left and right tables
612 lkind = asindices(lhdr, lkey)
613 rkind = asindices(rhdr, rkey)
614
615 # construct functions to extract key values from both tables
616 lgetk = comparable_itemgetter(*lkind)
617 rgetk = comparable_itemgetter(*rkind)
618
619 # construct group iterators for both tables
620 lgit = itertools.groupby(lit, key=lgetk)
621 rgit = itertools.groupby(rit, key=rgetk)
622 lrowgrp = []
623
624 # loop until *either* of the iterators is exhausted
625 lkval, rkval = Comparable(None), Comparable(None)
626 try:
627
628 # pick off initial row groups
629 lkval, lrowgrp = next(lgit)
630 rkval, _ = next(rgit)
631
632 while True:
633 if lkval < rkval:
634 for row in lrowgrp:
635 yield tuple(row)
636 # advance left
637 lkval, lrowgrp = next(lgit)
638 elif lkval > rkval:
639 # advance right
640 rkval, _ = next(rgit)
641 else:
642 # advance both
643 lkval, lrowgrp = next(lgit)
644 rkval, _ = next(rgit)
645
646 except StopIteration:
647 pass
648
649 # any left over?
650 if lkval > rkval:
651 # yield anything that got left hanging
652 for row in lrowgrp:
653 yield tuple(row)
654 # and the rest...
655 for lkval, lrowgrp in lgit:
656 for row in lrowgrp:
657 yield tuple(row)
658
659
660 def lookupjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
661 presorted=False, buffersize=None, tempdir=None, cache=True,
662 lprefix=None, rprefix=None):
663 """
664 Perform a left join, but where the key is not unique in the right-hand
665 table, arbitrarily choose the first row and ignore others. E.g.::
666
667 >>> import petl as etl
668 >>> table1 = [['id', 'color', 'cost'],
669 ... [1, 'blue', 12],
670 ... [2, 'red', 8],
671 ... [3, 'purple', 4]]
672 >>> table2 = [['id', 'shape', 'size'],
673 ... [1, 'circle', 'big'],
674 ... [1, 'circle', 'small'],
675 ... [2, 'square', 'tiny'],
676 ... [2, 'square', 'big'],
677 ... [3, 'ellipse', 'small'],
678 ... [3, 'ellipse', 'tiny']]
679 >>> table3 = etl.lookupjoin(table1, table2, key='id')
680 >>> table3
681 +----+----------+------+-----------+---------+
682 | id | color | cost | shape | size |
683 +====+==========+======+===========+=========+
684 | 1 | 'blue' | 12 | 'circle' | 'big' |
685 +----+----------+------+-----------+---------+
686 | 2 | 'red' | 8 | 'square' | 'tiny' |
687 +----+----------+------+-----------+---------+
688 | 3 | 'purple' | 4 | 'ellipse' | 'small' |
689 +----+----------+------+-----------+---------+
690
691 See also :func:`petl.transform.joins.leftjoin`.
692
693 .. versionchanged:: 1.7.16
694 To ensure correct results for tables with uneven rows, tables will be
695 squared up before joining to ensure correct results.
696
697 """
698
699 lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
700 return LookupJoinView(left, right, lkey, rkey, presorted=presorted,
701 missing=missing, buffersize=buffersize,
702 tempdir=tempdir, cache=cache,
703 lprefix=lprefix, rprefix=rprefix)
704
705
706 Table.lookupjoin = lookupjoin
707
708
709 class LookupJoinView(Table):
710
711 def __init__(self, left, right, lkey, rkey, presorted=False, missing=None,
712 buffersize=None, tempdir=None, cache=True,
713 lprefix=None, rprefix=None):
714 self.left = stack(left, missing=missing)
715 self.right = stack(right, missing=missing)
716 if not presorted:
717 self.left = sort(self.left, lkey, buffersize=buffersize,
718 tempdir=tempdir, cache=cache)
719 self.right = sort(self.right, rkey, buffersize=buffersize,
720 tempdir=tempdir, cache=cache)
721 self.lkey = lkey
722 self.rkey = rkey
723 self.missing = missing
724 self.lprefix = lprefix
725 self.rprefix = rprefix
726
727 def __iter__(self):
728 return iterlookupjoin(self.left, self.right, self.lkey, self.rkey,
729 missing=self.missing, lprefix=self.lprefix,
730 rprefix=self.rprefix)
731
732
733 def iterlookupjoin(left, right, lkey, rkey, missing=None, lprefix=None,
734 rprefix=None):
735 lit = iter(left)
736 rit = iter(right)
737
738 lhdr = next(lit)
739 rhdr = next(rit)
740
741 # determine indices of the key fields in left and right tables
742 lkind = asindices(lhdr, lkey)
743 rkind = asindices(rhdr, rkey)
744
745 # construct functions to extract key values from both tables
746 lgetk = operator.itemgetter(*lkind)
747 rgetk = operator.itemgetter(*rkind)
748
749 # determine indices of non-key fields in the right table
750 # (in the output, we only include key fields from the left table - we
751 # don't want to duplicate fields)
752 rvind = [i for i in range(len(rhdr)) if i not in rkind]
753 rgetv = rowgetter(*rvind)
754
755 # determine the output fields
756 if lprefix is None:
757 outhdr = list(lhdr)
758 else:
759 outhdr = [(text_type(lprefix) + text_type(f)) for f in lhdr]
760 if rprefix is None:
761 outhdr.extend(rgetv(rhdr))
762 else:
763 outhdr.extend([(text_type(rprefix) + text_type(f)) for f in rgetv(rhdr)])
764 yield tuple(outhdr)
765
766 # define a function to join two groups of rows
767 def joinrows(_lrowgrp, _rrowgrp):
768 if _rrowgrp is None:
769 for lrow in _lrowgrp:
770 outrow = list(lrow) # start with the left row
771 # extend with missing values in place of the right row
772 outrow.extend([missing] * len(rvind))
773 yield tuple(outrow)
774 else:
775 rrow = next(iter(_rrowgrp)) # pick first arbitrarily
776 for lrow in _lrowgrp:
777 # start with the left row
778 outrow = list(lrow)
779 # extend with non-key values from the right row
780 outrow.extend(rgetv(rrow))
781 yield tuple(outrow)
782
783 # construct group iterators for both tables
784 lgit = itertools.groupby(lit, key=lgetk)
785 rgit = itertools.groupby(rit, key=rgetk)
786 lrowgrp = []
787
788 # loop until *either* of the iterators is exhausted
789 lkval, rkval = None, None # initialise here to handle empty tables
790 try:
791
792 # pick off initial row groups
793 lkval, lrowgrp = next(lgit)
794 rkval, rrowgrp = next(rgit)
795
796 while True:
797 if lkval < rkval:
798 for row in joinrows(lrowgrp, None):
799 yield tuple(row)
800 # advance left
801 lkval, lrowgrp = next(lgit)
802 elif lkval > rkval:
803 # advance right
804 rkval, rrowgrp = next(rgit)
805 else:
806 for row in joinrows(lrowgrp, rrowgrp):
807 yield tuple(row)
808 # advance both
809 lkval, lrowgrp = next(lgit)
810 rkval, rrowgrp = next(rgit)
811
812 except StopIteration:
813 pass
814
815 # make sure any left rows remaining are yielded
816 if lkval > rkval:
817 # yield anything that got left hanging
818 for row in joinrows(lrowgrp, None):
819 yield tuple(row)
820 # yield the rest
821 for lkval, lrowgrp in lgit:
822 for row in joinrows(lrowgrp, None):
823 yield tuple(row)
824
825
826 def unjoin(table, value, key=None, autoincrement=(1, 1), presorted=False,
827 buffersize=None, tempdir=None, cache=True):
828 """
829 Split a table into two tables by reversing an inner join. E.g.::
830
831 >>> import petl as etl
832 >>> # join key is present in the table
833 ... table1 = (('foo', 'bar', 'baz'),
834 ... ('A', 1, 'apple'),
835 ... ('B', 1, 'apple'),
836 ... ('C', 2, 'orange'))
837 >>> table2, table3 = etl.unjoin(table1, 'baz', key='bar')
838 >>> table2
839 +-----+-----+
840 | foo | bar |
841 +=====+=====+
842 | 'A' | 1 |
843 +-----+-----+
844 | 'B' | 1 |
845 +-----+-----+
846 | 'C' | 2 |
847 +-----+-----+
848
849 >>> table3
850 +-----+----------+
851 | bar | baz |
852 +=====+==========+
853 | 1 | 'apple' |
854 +-----+----------+
855 | 2 | 'orange' |
856 +-----+----------+
857
858 >>> # an integer join key can also be reconstructed
859 ... table4 = (('foo', 'bar'),
860 ... ('A', 'apple'),
861 ... ('B', 'apple'),
862 ... ('C', 'orange'))
863 >>> table5, table6 = etl.unjoin(table4, 'bar')
864 >>> table5
865 +-----+--------+
866 | foo | bar_id |
867 +=====+========+
868 | 'A' | 1 |
869 +-----+--------+
870 | 'B' | 1 |
871 +-----+--------+
872 | 'C' | 2 |
873 +-----+--------+
874
875 >>> table6
876 +----+----------+
877 | id | bar |
878 +====+==========+
879 | 1 | 'apple' |
880 +----+----------+
881 | 2 | 'orange' |
882 +----+----------+
883
884 The `autoincrement` parameter controls how an integer join key is
885 reconstructed, and should be a tuple of (`start`, `step`).
886
887 """
888
889 if key is None:
890 # first sort the table by the value field
891 if presorted:
892 tbl_sorted = table
893 else:
894 tbl_sorted = sort(table, value, buffersize=buffersize,
895 tempdir=tempdir, cache=cache)
896 # on the left, return the original table but with the value field
897 # replaced by an incrementing integer
898 left = ConvertToIncrementingCounterView(tbl_sorted, value,
899 autoincrement)
900 # on the right, return a new table with distinct values from the
901 # given field
902 right = EnumerateDistinctView(tbl_sorted, value, autoincrement)
903 else:
904 # on the left, return distinct rows from the original table
905 # with the value field cut out
906 left = distinct(cutout(table, value))
907 # on the right, return distinct rows from the original table
908 # with all fields but the key and value cut out
909 right = distinct(cut(table, key, value))
910 return left, right
911
912
913 class ConvertToIncrementingCounterView(Table):
914
915 def __init__(self, tbl, value, autoincrement):
916 self.table = tbl
917 self.value = value
918 self.autoincrement = autoincrement
919
920 def __iter__(self):
921 it = iter(self.table)
922 hdr = next(it)
923 table = itertools.chain([hdr], it)
924 value = self.value
925 vidx = hdr.index(value)
926 outhdr = list(hdr)
927 outhdr[vidx] = '%s_id' % value
928 yield tuple(outhdr)
929 offset, multiplier = self.autoincrement
930 for n, (_, group) in enumerate(rowgroupby(table, value)):
931 for row in group:
932 outrow = list(row)
933 outrow[vidx] = (n * multiplier) + offset
934 yield tuple(outrow)
935
936
937 Table.unjoin = unjoin
938
939
940 class EnumerateDistinctView(Table):
941
942 def __init__(self, tbl, value, autoincrement):
943 self.table = tbl
944 self.value = value
945 self.autoincrement = autoincrement
946
947 def __iter__(self):
948 offset, multiplier = self.autoincrement
949 yield ('id', self.value)
950 for n, (v, _) in enumerate(rowgroupby(self.table, self.value)):
951 yield ((n * multiplier) + offset, v)