Debian Codegraph @

petl/transform/basics.py

raw
1 from __future__ import absolute_import, print_function, division
2
3
4 # standard library dependencies
5 from itertools import islice, chain
6 from collections import deque
7 from itertools import count
8 from petl.compat import izip, izip_longest, next, string_types, text_type
9
10
11 # internal dependencies
12 from petl.util.base import asindices, rowgetter, Record, Table
13
14
15 import logging
16 logger = logging.getLogger(__name__)
17 warning = logger.warning
18 info = logger.info
19 debug = logger.debug
20
21
22 def cut(table, *args, **kwargs):
23 """
24 Choose and/or re-order fields. E.g.::
25
26 >>> import petl as etl
27 >>> table1 = [['foo', 'bar', 'baz'],
28 ... ['A', 1, 2.7],
29 ... ['B', 2, 3.4],
30 ... ['B', 3, 7.8],
31 ... ['D', 42, 9.0],
32 ... ['E', 12]]
33 >>> table2 = etl.cut(table1, 'foo', 'baz')
34 >>> table2
35 +-----+------+
36 | foo | baz |
37 +=====+======+
38 | 'A' | 2.7 |
39 +-----+------+
40 | 'B' | 3.4 |
41 +-----+------+
42 | 'B' | 7.8 |
43 +-----+------+
44 | 'D' | 9.0 |
45 +-----+------+
46 | 'E' | None |
47 +-----+------+
48
49 >>> # fields can also be specified by index, starting from zero
50 ... table3 = etl.cut(table1, 0, 2)
51 >>> table3
52 +-----+------+
53 | foo | baz |
54 +=====+======+
55 | 'A' | 2.7 |
56 +-----+------+
57 | 'B' | 3.4 |
58 +-----+------+
59 | 'B' | 7.8 |
60 +-----+------+
61 | 'D' | 9.0 |
62 +-----+------+
63 | 'E' | None |
64 +-----+------+
65
66 >>> # field names and indices can be mixed
67 ... table4 = etl.cut(table1, 'bar', 0)
68 >>> table4
69 +-----+-----+
70 | bar | foo |
71 +=====+=====+
72 | 1 | 'A' |
73 +-----+-----+
74 | 2 | 'B' |
75 +-----+-----+
76 | 3 | 'B' |
77 +-----+-----+
78 | 42 | 'D' |
79 +-----+-----+
80 | 12 | 'E' |
81 +-----+-----+
82
83 >>> # select a range of fields
84 ... table5 = etl.cut(table1, *range(0, 2))
85 >>> table5
86 +-----+-----+
87 | foo | bar |
88 +=====+=====+
89 | 'A' | 1 |
90 +-----+-----+
91 | 'B' | 2 |
92 +-----+-----+
93 | 'B' | 3 |
94 +-----+-----+
95 | 'D' | 42 |
96 +-----+-----+
97 | 'E' | 12 |
98 +-----+-----+
99
100 Note that any short rows will be padded with `None` values (or whatever is
101 provided via the `missing` keyword argument).
102
103 See also :func:`petl.transform.basics.cutout`.
104
105 """
106
107 # support passing a single list or tuple of fields
108 if len(args) == 1 and isinstance(args[0], (list, tuple)):
109 args = args[0]
110
111 return CutView(table, args, **kwargs)
112
113
114 Table.cut = cut
115
116
117 class CutView(Table):
118
119 def __init__(self, source, spec, missing=None):
120 self.source = source
121 self.spec = spec
122 self.missing = missing
123
124 def __iter__(self):
125 return itercut(self.source, self.spec, self.missing)
126
127
128 def itercut(source, spec, missing=None):
129 it = iter(source)
130 spec = tuple(spec) # make sure no-one can change midstream
131
132 # convert field selection into field indices
133 try:
134 hdr = next(it)
135 except StopIteration:
136 hdr = []
137 indices = asindices(hdr, spec)
138
139 # define a function to transform each row in the source data
140 # according to the field selection
141 transform = rowgetter(*indices)
142
143 # yield the transformed header
144 yield transform(hdr)
145
146 # construct the transformed data
147 for row in it:
148 try:
149 yield transform(row)
150 except IndexError:
151 # row is short, let's be kind and fill in any missing fields
152 yield tuple(row[i] if i < len(row) else missing for i in indices)
153
154
155 def cutout(table, *args, **kwargs):
156 """
157 Remove fields. E.g.::
158
159 >>> import petl as etl
160 >>> table1 = [['foo', 'bar', 'baz'],
161 ... ['A', 1, 2.7],
162 ... ['B', 2, 3.4],
163 ... ['B', 3, 7.8],
164 ... ['D', 42, 9.0],
165 ... ['E', 12]]
166 >>> table2 = etl.cutout(table1, 'bar')
167 >>> table2
168 +-----+------+
169 | foo | baz |
170 +=====+======+
171 | 'A' | 2.7 |
172 +-----+------+
173 | 'B' | 3.4 |
174 +-----+------+
175 | 'B' | 7.8 |
176 +-----+------+
177 | 'D' | 9.0 |
178 +-----+------+
179 | 'E' | None |
180 +-----+------+
181
182 See also :func:`petl.transform.basics.cut`.
183
184 """
185
186 return CutOutView(table, args, **kwargs)
187
188
189 Table.cutout = cutout
190
191
192 class CutOutView(Table):
193
194 def __init__(self, source, spec, missing=None):
195 self.source = source
196 self.spec = spec
197 self.missing = missing
198
199 def __iter__(self):
200 return itercutout(self.source, self.spec, self.missing)
201
202
203 def itercutout(source, spec, missing=None):
204 it = iter(source)
205 spec = tuple(spec) # make sure no-one can change midstream
206
207 # convert field selection into field indices
208 try:
209 hdr = next(it)
210 except StopIteration:
211 hdr = []
212 indicesout = asindices(hdr, spec)
213 indices = [i for i in range(len(hdr)) if i not in indicesout]
214
215 # define a function to transform each row in the source data
216 # according to the field selection
217 transform = rowgetter(*indices)
218
219 # yield the transformed header
220 yield transform(hdr)
221
222 # construct the transformed data
223 for row in it:
224 try:
225 yield transform(row)
226 except IndexError:
227 # row is short, let's be kind and fill in any missing fields
228 yield tuple(row[i] if i < len(row) else missing for i in indices)
229
230
231 def cat(*tables, **kwargs):
232 """
233 Concatenate tables. E.g.::
234
235 >>> import petl as etl
236 >>> table1 = [['foo', 'bar'],
237 ... [1, 'A'],
238 ... [2, 'B']]
239 >>> table2 = [['bar', 'baz'],
240 ... ['C', True],
241 ... ['D', False]]
242 >>> table3 = etl.cat(table1, table2)
243 >>> table3
244 +------+-----+-------+
245 | foo | bar | baz |
246 +======+=====+=======+
247 | 1 | 'A' | None |
248 +------+-----+-------+
249 | 2 | 'B' | None |
250 +------+-----+-------+
251 | None | 'C' | True |
252 +------+-----+-------+
253 | None | 'D' | False |
254 +------+-----+-------+
255
256 >>> # can also be used to square up a single table with uneven rows
257 ... table4 = [['foo', 'bar', 'baz'],
258 ... ['A', 1, 2],
259 ... ['B', '2', '3.4'],
260 ... [u'B', u'3', u'7.8', True],
261 ... ['D', 'xyz', 9.0],
262 ... ['E', None]]
263 >>> table5 = etl.cat(table4)
264 >>> table5
265 +-----+-------+-------+
266 | foo | bar | baz |
267 +=====+=======+=======+
268 | 'A' | 1 | 2 |
269 +-----+-------+-------+
270 | 'B' | '2' | '3.4' |
271 +-----+-------+-------+
272 | 'B' | '3' | '7.8' |
273 +-----+-------+-------+
274 | 'D' | 'xyz' | 9.0 |
275 +-----+-------+-------+
276 | 'E' | None | None |
277 +-----+-------+-------+
278
279 >>> # use the header keyword argument to specify a fixed set of fields
280 ... table6 = [['bar', 'foo'],
281 ... ['A', 1],
282 ... ['B', 2]]
283 >>> table7 = etl.cat(table6, header=['A', 'foo', 'B', 'bar', 'C'])
284 >>> table7
285 +------+-----+------+-----+------+
286 | A | foo | B | bar | C |
287 +======+=====+======+=====+======+
288 | None | 1 | None | 'A' | None |
289 +------+-----+------+-----+------+
290 | None | 2 | None | 'B' | None |
291 +------+-----+------+-----+------+
292
293 >>> # using the header keyword argument with two input tables
294 ... table8 = [['bar', 'foo'],
295 ... ['A', 1],
296 ... ['B', 2]]
297 >>> table9 = [['bar', 'baz'],
298 ... ['C', True],
299 ... ['D', False]]
300 >>> table10 = etl.cat(table8, table9, header=['A', 'foo', 'B', 'bar', 'C'])
301 >>> table10
302 +------+------+------+-----+------+
303 | A | foo | B | bar | C |
304 +======+======+======+=====+======+
305 | None | 1 | None | 'A' | None |
306 +------+------+------+-----+------+
307 | None | 2 | None | 'B' | None |
308 +------+------+------+-----+------+
309 | None | None | None | 'C' | None |
310 +------+------+------+-----+------+
311 | None | None | None | 'D' | None |
312 +------+------+------+-----+------+
313
314 Note that the tables do not need to share exactly the same fields, any
315 missing fields will be padded with `None` or whatever is provided via the
316 `missing` keyword argument.
317
318 Note that this function can be used with a single table argument, in which
319 case it has the effect of ensuring all data rows are the same length as
320 the header row, truncating any long rows and padding any short rows with
321 the value of the `missing` keyword argument.
322
323 By default, the fields for the output table will be determined as the
324 union of all fields found in the input tables. Use the `header` keyword
325 argument to override this behaviour and specify a fixed set of fields for
326 the output table.
327
328 """
329
330 return CatView(tables, **kwargs)
331
332
333 Table.cat = cat
334
335
336 class CatView(Table):
337
338 def __init__(self, sources, missing=None, header=None):
339 self.sources = sources
340 self.missing = missing
341 self.header = header
342
343 def __iter__(self):
344 return itercat(self.sources, self.missing, self.header)
345
346
347 def itercat(sources, missing, header):
348 its = [iter(t) for t in sources]
349 hdrs = []
350 for it in its:
351 try:
352 hdrs.append(list(next(it)))
353 except StopIteration:
354 hdrs.append([])
355
356 if header is None:
357 # determine output fields by gathering all fields found in the sources
358 outhdr = list(hdrs[0])
359 for hdr in hdrs[1:]:
360 for h in hdr:
361 if h not in outhdr:
362 # add any new fields as we find them
363 outhdr.append(h)
364 else:
365 # predetermined output fields
366 outhdr = header
367 yield tuple(outhdr)
368
369 # output data rows
370 for hdr, it in zip(hdrs, its):
371
372 # now construct and yield the data rows
373 for row in it:
374 outrow = list()
375 for h in outhdr:
376 val = missing
377 try:
378 val = row[hdr.index(h)]
379 except IndexError:
380 # short row
381 pass
382 except ValueError:
383 # field not in table
384 pass
385 outrow.append(val)
386 yield tuple(outrow)
387
388
389 def stack(*tables, **kwargs):
390 """Concatenate tables, without trying to match headers. E.g.::
391
392 >>> import petl as etl
393 >>> table1 = [['foo', 'bar'],
394 ... [1, 'A'],
395 ... [2, 'B']]
396 >>> table2 = [['bar', 'baz'],
397 ... ['C', True],
398 ... ['D', False]]
399 >>> table3 = etl.stack(table1, table2)
400 >>> table3
401 +-----+-------+
402 | foo | bar |
403 +=====+=======+
404 | 1 | 'A' |
405 +-----+-------+
406 | 2 | 'B' |
407 +-----+-------+
408 | 'C' | True |
409 +-----+-------+
410 | 'D' | False |
411 +-----+-------+
412
413 >>> # can also be used to square up a single table with uneven rows
414 ... table4 = [['foo', 'bar', 'baz'],
415 ... ['A', 1, 2],
416 ... ['B', '2', '3.4'],
417 ... [u'B', u'3', u'7.8', True],
418 ... ['D', 'xyz', 9.0],
419 ... ['E', None]]
420 >>> table5 = etl.stack(table4)
421 >>> table5
422 +-----+-------+-------+
423 | foo | bar | baz |
424 +=====+=======+=======+
425 | 'A' | 1 | 2 |
426 +-----+-------+-------+
427 | 'B' | '2' | '3.4' |
428 +-----+-------+-------+
429 | 'B' | '3' | '7.8' |
430 +-----+-------+-------+
431 | 'D' | 'xyz' | 9.0 |
432 +-----+-------+-------+
433 | 'E' | None | None |
434 +-----+-------+-------+
435
436 Similar to :func:`petl.transform.basics.cat` except that no attempt is
437 made to align fields from different tables. Data rows are simply emitted
438 in order, trimmed or padded to the length of the header row from the
439 first table.
440
441 .. versionadded:: 1.1.0
442
443 """
444
445 return StackView(tables, **kwargs)
446
447
448 Table.stack = stack
449
450
451 class StackView(Table):
452
453 def __init__(self, sources, missing=None, trim=True, pad=True):
454 self.sources = sources
455 self.missing = missing
456 self.trim = trim
457 self.pad = pad
458
459 def __iter__(self):
460 return iterstack(self.sources, self.missing, self.trim, self.pad)
461
462
463 def iterstack(sources, missing, trim, pad):
464 its = [iter(t) for t in sources]
465 hdrs = []
466 for it in its:
467 try:
468 hdrs.append(next(it))
469 except StopIteration:
470 hdrs.append([])
471 hdr = hdrs[0]
472 n = len(hdr)
473 yield tuple(hdr)
474 for it in its:
475 for row in it:
476 outrow = tuple(row)
477 if trim:
478 outrow = outrow[:n]
479 if pad and len(outrow) < n:
480 outrow += (missing,) * (n - len(outrow))
481 yield outrow
482
483
484 def addfield(table, field, value=None, index=None, missing=None):
485 """
486 Add a field with a fixed or calculated value. E.g.::
487
488 >>> import petl as etl
489 >>> table1 = [['foo', 'bar'],
490 ... ['M', 12],
491 ... ['F', 34],
492 ... ['-', 56]]
493 >>> # using a fixed value
494 ... table2 = etl.addfield(table1, 'baz', 42)
495 >>> table2
496 +-----+-----+-----+
497 | foo | bar | baz |
498 +=====+=====+=====+
499 | 'M' | 12 | 42 |
500 +-----+-----+-----+
501 | 'F' | 34 | 42 |
502 +-----+-----+-----+
503 | '-' | 56 | 42 |
504 +-----+-----+-----+
505
506 >>> # calculating the value
507 ... table2 = etl.addfield(table1, 'baz', lambda rec: rec['bar'] * 2)
508 >>> table2
509 +-----+-----+-----+
510 | foo | bar | baz |
511 +=====+=====+=====+
512 | 'M' | 12 | 24 |
513 +-----+-----+-----+
514 | 'F' | 34 | 68 |
515 +-----+-----+-----+
516 | '-' | 56 | 112 |
517 +-----+-----+-----+
518
519 Use the `index` parameter to control the position of the inserted field.
520
521 """
522
523 return AddFieldView(table, field, value=value, index=index,
524 missing=missing)
525
526
527 Table.addfield = addfield
528
529
530 class AddFieldView(Table):
531
532 def __init__(self, source, field, value=None, index=None, missing=None):
533 # ensure rows are all the same length
534 self.source = stack(source, missing=missing)
535 self.field = field
536 self.value = value
537 self.index = index
538
539 def __iter__(self):
540 return iteraddfield(self.source, self.field, self.value, self.index)
541
542
543 def iteraddfield(source, field, value, index):
544 it = iter(source)
545 try:
546 hdr = next(it)
547 except StopIteration:
548 hdr = []
549 flds = list(map(text_type, hdr))
550
551 # determine index of new field
552 if index is None:
553 index = len(hdr)
554
555 # construct output fields
556 outhdr = list(hdr)
557 outhdr.insert(index, field)
558 yield tuple(outhdr)
559
560 if callable(value):
561 # wrap rows as records if using calculated value
562 it = (Record(row, flds) for row in it)
563 for row in it:
564 outrow = list(row)
565 v = value(row)
566 outrow.insert(index, v)
567 yield tuple(outrow)
568 else:
569 for row in it:
570 outrow = list(row)
571 outrow.insert(index, value)
572 yield tuple(outrow)
573
574
575 def addfields(table, field_defs, missing=None):
576 """
577 Add fields with fixed or calculated values. E.g.::
578
579 >>> import petl as etl
580 >>> table1 = [['foo', 'bar'],
581 ... ['M', 12],
582 ... ['F', 34],
583 ... ['-', 56]]
584 >>> # using a fixed value or a calculation
585 ... table2 = etl.addfields(table1,
586 ... [('baz', 42),
587 ... ('luhrmann', lambda rec: rec['bar'] * 2)])
588 >>> table2
589 +-----+-----+-----+----------+
590 | foo | bar | baz | luhrmann |
591 +=====+=====+=====+==========+
592 | 'M' | 12 | 42 | 24 |
593 +-----+-----+-----+----------+
594 | 'F' | 34 | 42 | 68 |
595 +-----+-----+-----+----------+
596 | '-' | 56 | 42 | 112 |
597 +-----+-----+-----+----------+
598
599 >>> # you can specify an index as a 3rd item in each tuple -- indicies
600 ... # are evaluated in order.
601 ... table2 = etl.addfields(table1,
602 ... [('baz', 42, 0),
603 ... ('luhrmann', lambda rec: rec['bar'] * 2, 0)])
604 >>> table2
605 +----------+-----+-----+-----+
606 | luhrmann | baz | foo | bar |
607 +==========+=====+=====+=====+
608 | 24 | 42 | 'M' | 12 |
609 +----------+-----+-----+-----+
610 | 68 | 42 | 'F' | 34 |
611 +----------+-----+-----+-----+
612 | 112 | 42 | '-' | 56 |
613 +----------+-----+-----+-----+
614
615 """
616
617 return AddFieldsView(table, field_defs, missing=missing)
618
619
620 Table.addfields = addfields
621
622
623 class AddFieldsView(Table):
624
625 def __init__(self, source, field_defs, missing=None):
626 # ensure rows are all the same length
627 self.source = stack(source, missing=missing)
628 # convert tuples to FieldDefinitions, if necessary
629 self.field_defs = field_defs
630
631 def __iter__(self):
632 return iteraddfields(self.source, self.field_defs)
633
634
635 def iteraddfields(source, field_defs):
636 it = iter(source)
637 try:
638 hdr = next(it)
639 except StopIteration:
640 hdr = []
641 flds = list(map(text_type, hdr))
642
643 # initialize output fields and indices
644 outhdr = list(hdr)
645 value_indexes = []
646
647 for fdef in field_defs:
648 # determine the defined field index
649 if len(fdef) == 2:
650 name, value = fdef
651 index = len(outhdr)
652 else:
653 name, value, index = fdef
654
655 # insert the name into the header at the appropriate index
656 outhdr.insert(index, name)
657
658 # remember the value/index pairs for later
659 value_indexes.append((value, index))
660 yield tuple(outhdr)
661
662 for row in it:
663 outrow = list(row)
664
665 # add each defined field into the row at the appropriate index
666 for value, index in value_indexes:
667 if callable(value):
668 # wrap row as record if using calculated value
669 row = Record(row, flds)
670 v = value(row)
671 outrow.insert(index, v)
672 else:
673 outrow.insert(index, value)
674
675 yield tuple(outrow)
676
677
678 def rowslice(table, *sliceargs):
679 """
680 Choose a subsequence of data rows. E.g.::
681
682 >>> import petl as etl
683 >>> table1 = [['foo', 'bar'],
684 ... ['a', 1],
685 ... ['b', 2],
686 ... ['c', 5],
687 ... ['d', 7],
688 ... ['f', 42]]
689 >>> table2 = etl.rowslice(table1, 2)
690 >>> table2
691 +-----+-----+
692 | foo | bar |
693 +=====+=====+
694 | 'a' | 1 |
695 +-----+-----+
696 | 'b' | 2 |
697 +-----+-----+
698
699 >>> table3 = etl.rowslice(table1, 1, 4)
700 >>> table3
701 +-----+-----+
702 | foo | bar |
703 +=====+=====+
704 | 'b' | 2 |
705 +-----+-----+
706 | 'c' | 5 |
707 +-----+-----+
708 | 'd' | 7 |
709 +-----+-----+
710
711 >>> table4 = etl.rowslice(table1, 0, 5, 2)
712 >>> table4
713 +-----+-----+
714 | foo | bar |
715 +=====+=====+
716 | 'a' | 1 |
717 +-----+-----+
718 | 'c' | 5 |
719 +-----+-----+
720 | 'f' | 42 |
721 +-----+-----+
722
723 Positional arguments are used to slice the data rows. The `sliceargs` are
724 passed through to :func:`itertools.islice`.
725
726 See also :func:`petl.transform.basics.head`,
727 :func:`petl.transform.basics.tail`.
728
729 """
730
731 return RowSliceView(table, *sliceargs)
732
733
734 Table.rowslice = rowslice
735
736
737 class RowSliceView(Table):
738
739 def __init__(self, source, *sliceargs):
740 self.source = source
741 if not sliceargs:
742 self.sliceargs = (None,)
743 else:
744 self.sliceargs = sliceargs
745
746 def __iter__(self):
747 return iterrowslice(self.source, self.sliceargs)
748
749
750 def iterrowslice(source, sliceargs):
751 it = iter(source)
752 try:
753 yield tuple(next(it)) # fields
754 except StopIteration:
755 return
756 for row in islice(it, *sliceargs):
757 yield tuple(row)
758
759
760 def head(table, n=5):
761 """
762 Select the first `n` data rows. E.g.::
763
764 >>> import petl as etl
765 >>> table1 = [['foo', 'bar'],
766 ... ['a', 1],
767 ... ['b', 2],
768 ... ['c', 5],
769 ... ['d', 7],
770 ... ['f', 42],
771 ... ['f', 3],
772 ... ['h', 90]]
773 >>> table2 = etl.head(table1, 4)
774 >>> table2
775 +-----+-----+
776 | foo | bar |
777 +=====+=====+
778 | 'a' | 1 |
779 +-----+-----+
780 | 'b' | 2 |
781 +-----+-----+
782 | 'c' | 5 |
783 +-----+-----+
784 | 'd' | 7 |
785 +-----+-----+
786
787 See also :func:`petl.transform.basics.tail`,
788 :func:`petl.transform.basics.rowslice`.
789
790 """
791
792 return rowslice(table, n)
793
794
795 Table.head = head
796
797
798 def tail(table, n=5):
799 """
800 Select the last `n` data rows. E.g.::
801
802 >>> import petl as etl
803 >>> table1 = [['foo', 'bar'],
804 ... ['a', 1],
805 ... ['b', 2],
806 ... ['c', 5],
807 ... ['d', 7],
808 ... ['f', 42],
809 ... ['f', 3],
810 ... ['h', 90],
811 ... ['k', 12],
812 ... ['l', 77],
813 ... ['q', 2]]
814 >>> table2 = etl.tail(table1, 4)
815 >>> table2
816 +-----+-----+
817 | foo | bar |
818 +=====+=====+
819 | 'h' | 90 |
820 +-----+-----+
821 | 'k' | 12 |
822 +-----+-----+
823 | 'l' | 77 |
824 +-----+-----+
825 | 'q' | 2 |
826 +-----+-----+
827
828 See also :func:`petl.transform.basics.head`,
829 :func:`petl.transform.basics.rowslice`.
830
831 """
832
833 return TailView(table, n)
834
835
836 Table.tail = tail
837
838
839 class TailView(Table):
840
841 def __init__(self, source, n):
842 self.source = source
843 self.n = n
844
845 def __iter__(self):
846 return itertail(self.source, self.n)
847
848
849 def itertail(source, n):
850 it = iter(source)
851 try:
852 yield tuple(next(it)) # fields
853 except StopIteration:
854 return # stop generating
855 cache = deque()
856 for row in it:
857 cache.append(row)
858 if len(cache) > n:
859 cache.popleft()
860 for row in cache:
861 yield tuple(row)
862
863
864 def skipcomments(table, prefix):
865 """
866 Skip any row where the first value is a string and starts with
867 `prefix`. E.g.::
868
869 >>> import petl as etl
870 >>> table1 = [['##aaa', 'bbb', 'ccc'],
871 ... ['##mmm',],
872 ... ['#foo', 'bar'],
873 ... ['##nnn', 1],
874 ... ['a', 1],
875 ... ['b', 2]]
876 >>> table2 = etl.skipcomments(table1, '##')
877 >>> table2
878 +------+-----+
879 | #foo | bar |
880 +======+=====+
881 | 'a' | 1 |
882 +------+-----+
883 | 'b' | 2 |
884 +------+-----+
885
886 Use the `prefix` parameter to determine which string to consider as
887 indicating a comment.
888
889 """
890
891 return SkipCommentsView(table, prefix)
892
893
894 Table.skipcomments = skipcomments
895
896
897 class SkipCommentsView(Table):
898
899 def __init__(self, source, prefix):
900 self.source = source
901 self.prefix = prefix
902
903 def __iter__(self):
904 return iterskipcomments(self.source, self.prefix)
905
906
907 def iterskipcomments(source, prefix):
908 return (row for row in source
909 if (len(row) > 0
910 and not(isinstance(row[0], string_types)
911 and row[0].startswith(prefix))))
912
913
914 def movefield(table, field, index):
915 """
916 Move a field to a new position.
917
918 """
919
920 return MoveFieldView(table, field, index)
921
922
923 Table.movefield = movefield
924
925
926 class MoveFieldView(Table):
927
928 def __init__(self, table, field, index, missing=None):
929 self.table = table
930 self.field = field
931 self.index = index
932 self.missing = missing
933
934 def __iter__(self):
935 it = iter(self.table)
936
937 # determine output fields
938 try:
939 hdr = next(it)
940 except StopIteration:
941 hdr = []
942 outhdr = [f for f in hdr if f != self.field]
943 outhdr.insert(self.index, self.field)
944 yield tuple(outhdr)
945
946 # define a function to transform each row in the source data
947 # according to the field selection
948 outflds = list(map(str, outhdr))
949 indices = asindices(hdr, outflds)
950 transform = rowgetter(*indices)
951
952 # construct the transformed data
953 for row in it:
954 try:
955 yield transform(row)
956 except IndexError:
957 # row is short, let's be kind and fill in any missing fields
958 yield tuple(row[i] if i < len(row) else self.missing
959 for i in indices)
960
961
962 def annex(*tables, **kwargs):
963 """
964 Join two or more tables by row order. E.g.::
965
966 >>> import petl as etl
967 >>> table1 = [['foo', 'bar'],
968 ... ['A', 9],
969 ... ['C', 2],
970 ... ['F', 1]]
971 >>> table2 = [['foo', 'baz'],
972 ... ['B', 3],
973 ... ['D', 10]]
974 >>> table3 = etl.annex(table1, table2)
975 >>> table3
976 +-----+-----+------+------+
977 | foo | bar | foo | baz |
978 +=====+=====+======+======+
979 | 'A' | 9 | 'B' | 3 |
980 +-----+-----+------+------+
981 | 'C' | 2 | 'D' | 10 |
982 +-----+-----+------+------+
983 | 'F' | 1 | None | None |
984 +-----+-----+------+------+
985
986 See also :func:`petl.transform.joins.join`.
987
988 """
989
990 return AnnexView(tables, **kwargs)
991
992
993 Table.annex = annex
994
995
996 class AnnexView(Table):
997
998 def __init__(self, tables, missing=None):
999 self.tables = tables
1000 self.missing = missing
1001
1002 def __iter__(self):
1003 return iterannex(self.tables, self.missing)
1004
1005
1006 def iterannex(tables, missing):
1007 its = [iter(t) for t in tables]
1008 hdrs = []
1009 for it in its:
1010 try:
1011 hdrs.append(next(it))
1012 except StopIteration:
1013 hdrs.append([])
1014 outhdr = tuple(chain(*hdrs))
1015 yield outhdr
1016 for rows in izip_longest(*its):
1017 outrow = list()
1018 for i, row in enumerate(rows):
1019 lh = len(hdrs[i])
1020 if row is None: # handle uneven length tables
1021 row = [missing] * len(hdrs[i])
1022 else:
1023 lr = len(row)
1024 if lr < lh: # handle short rows
1025 row = list(row)
1026 row.extend([missing] * (lh-lr))
1027 elif lr > lh: # handle long rows
1028 row = row[:lh]
1029 outrow.extend(row)
1030 yield tuple(outrow)
1031
1032
1033 def addrownumbers(table, start=1, step=1, field='row'):
1034 """
1035 Add a field of row numbers. E.g.::
1036
1037 >>> import petl as etl
1038 >>> table1 = [['foo', 'bar'],
1039 ... ['A', 9],
1040 ... ['C', 2],
1041 ... ['F', 1]]
1042 >>> table2 = etl.addrownumbers(table1)
1043 >>> table2
1044 +-----+-----+-----+
1045 | row | foo | bar |
1046 +=====+=====+=====+
1047 | 1 | 'A' | 9 |
1048 +-----+-----+-----+
1049 | 2 | 'C' | 2 |
1050 +-----+-----+-----+
1051 | 3 | 'F' | 1 |
1052 +-----+-----+-----+
1053
1054 Parameters `start` and `step` control the numbering.
1055
1056 """
1057
1058 return AddRowNumbersView(table, start, step, field)
1059
1060
1061 Table.addrownumbers = addrownumbers
1062
1063
1064 class AddRowNumbersView(Table):
1065
1066 def __init__(self, table, start=1, step=1, field='row'):
1067 self.table = table
1068 self.start = start
1069 self.step = step
1070 self.field = field
1071
1072 def __iter__(self):
1073 return iteraddrownumbers(self.table, self.start, self.step, self.field)
1074
1075
1076 def iteraddrownumbers(table, start, step, field):
1077 it = iter(table)
1078 try:
1079 hdr = next(it)
1080 except StopIteration:
1081 hdr = []
1082 outhdr = [field]
1083 outhdr.extend(hdr)
1084 yield tuple(outhdr)
1085 for row, n in izip(it, count(start, step)):
1086 outrow = [n]
1087 outrow.extend(row)
1088 yield tuple(outrow)
1089
1090
1091 def addcolumn(table, field, col, index=None, missing=None):
1092 """
1093 Add a column of data to the table. E.g.::
1094
1095 >>> import petl as etl
1096 >>> table1 = [['foo', 'bar'],
1097 ... ['A', 1],
1098 ... ['B', 2]]
1099 >>> col = [True, False]
1100 >>> table2 = etl.addcolumn(table1, 'baz', col)
1101 >>> table2
1102 +-----+-----+-------+
1103 | foo | bar | baz |
1104 +=====+=====+=======+
1105 | 'A' | 1 | True |
1106 +-----+-----+-------+
1107 | 'B' | 2 | False |
1108 +-----+-----+-------+
1109
1110 Use the `index` parameter to control the position of the new column.
1111
1112 """
1113
1114 return AddColumnView(table, field, col, index=index, missing=missing)
1115
1116
1117 Table.addcolumn = addcolumn
1118
1119
1120 class AddColumnView(Table):
1121
1122 def __init__(self, table, field, col, index=None, missing=None):
1123 self._table = table
1124 self._field = field
1125 self._col = col
1126 self._index = index
1127 self._missing = missing
1128
1129 def __iter__(self):
1130 return iteraddcolumn(self._table, self._field, self._col,
1131 self._index, self._missing)
1132
1133
1134 def iteraddcolumn(table, field, col, index, missing):
1135 it = iter(table)
1136 try:
1137 hdr = next(it)
1138 except StopIteration:
1139 hdr = []
1140
1141 # determine position of new column
1142 if index is None:
1143 index = len(hdr)
1144
1145 # construct output header
1146 outhdr = list(hdr)
1147 outhdr.insert(index, field)
1148 yield tuple(outhdr)
1149
1150 # construct output data
1151 for row, val in izip_longest(it, col, fillvalue=missing):
1152 # run out of rows?
1153 if row == missing:
1154 row = [missing] * len(hdr)
1155 outrow = list(row)
1156 outrow.insert(index, val)
1157 yield tuple(outrow)
1158
1159
1160 class TransformError(Exception):
1161 pass
1162
1163
1164 def addfieldusingcontext(table, field, query):
1165 """
1166 Like :func:`petl.transform.basics.addfield` but the `query` function is
1167 passed the previous, current and next rows, so values may be calculated
1168 based on data in adjacent rows. E.g.::
1169
1170 >>> import petl as etl
1171 >>> table1 = [['foo', 'bar'],
1172 ... ['A', 1],
1173 ... ['B', 4],
1174 ... ['C', 5],
1175 ... ['D', 9]]
1176 >>> def upstream(prv, cur, nxt):
1177 ... if prv is None:
1178 ... return None
1179 ... else:
1180 ... return cur.bar - prv.bar
1181 ...
1182 >>> def downstream(prv, cur, nxt):
1183 ... if nxt is None:
1184 ... return None
1185 ... else:
1186 ... return nxt.bar - cur.bar
1187 ...
1188 >>> table2 = etl.addfieldusingcontext(table1, 'baz', upstream)
1189 >>> table3 = etl.addfieldusingcontext(table2, 'quux', downstream)
1190 >>> table3
1191 +-----+-----+------+------+
1192 | foo | bar | baz | quux |
1193 +=====+=====+======+======+
1194 | 'A' | 1 | None | 3 |
1195 +-----+-----+------+------+
1196 | 'B' | 4 | 3 | 1 |
1197 +-----+-----+------+------+
1198 | 'C' | 5 | 1 | 4 |
1199 +-----+-----+------+------+
1200 | 'D' | 9 | 4 | None |
1201 +-----+-----+------+------+
1202
1203 The `field` parameter is the name of the field to be added. The `query`
1204 parameter is a function operating on the current, previous and next rows
1205 and returning the value.
1206
1207 """
1208
1209 return AddFieldUsingContextView(table, field, query)
1210
1211
1212 Table.addfieldusingcontext = addfieldusingcontext
1213
1214
1215 class AddFieldUsingContextView(Table):
1216
1217 def __init__(self, table, field, query):
1218 self.table = table
1219 self.field = field
1220 self.query = query
1221
1222 def __iter__(self):
1223 return iteraddfieldusingcontext(self.table, self.field, self.query)
1224
1225
1226 def iteraddfieldusingcontext(table, field, query):
1227 it = iter(table)
1228 try:
1229 hdr = tuple(next(it))
1230 except StopIteration:
1231 hdr = ()
1232 flds = list(map(text_type, hdr))
1233 yield hdr + (field,)
1234 flds.append(field)
1235 it = (Record(row, flds) for row in it)
1236 prv = None
1237 try:
1238 cur = next(it)
1239 except StopIteration:
1240 return # no more items
1241 for nxt in it:
1242 v = query(prv, cur, nxt)
1243 yield tuple(cur) + (v,)
1244 prv = Record(tuple(cur) + (v,), flds)
1245 cur = nxt
1246 # handle last row
1247 v = query(prv, cur, None)
1248 yield tuple(cur) + (v,)