| 1 |
# -*- coding: utf-8 -*- |
| 2 |
from __future__ import division, print_function, absolute_import |
| 3 |
|
| 4 |
|
| 5 |
import locale |
| 6 |
import codecs |
| 7 |
from petl.compat import izip_longest |
| 8 |
|
| 9 |
from petl.util.base import Table |
| 10 |
|
| 11 |
|
| 12 |
def getcodec(encoding): |
| 13 |
if encoding is None: |
| 14 |
encoding = locale.getpreferredencoding() |
| 15 |
codec = codecs.lookup(encoding) |
| 16 |
return codec |
| 17 |
|
| 18 |
|
| 19 |
def fromcolumns(cols, header=None, missing=None): |
| 20 |
"""View a sequence of columns as a table, e.g.:: |
| 21 |
|
| 22 |
>>> import petl as etl |
| 23 |
>>> cols = [[0, 1, 2], ['a', 'b', 'c']] |
| 24 |
>>> tbl = etl.fromcolumns(cols) |
| 25 |
>>> tbl |
| 26 |
+----+-----+ |
| 27 |
| f0 | f1 | |
| 28 |
+====+=====+ |
| 29 |
| 0 | 'a' | |
| 30 |
+----+-----+ |
| 31 |
| 1 | 'b' | |
| 32 |
+----+-----+ |
| 33 |
| 2 | 'c' | |
| 34 |
+----+-----+ |
| 35 |
|
| 36 |
If columns are not the same length, values will be padded to the length |
| 37 |
of the longest column with `missing`, which is None by default, e.g.:: |
| 38 |
|
| 39 |
>>> cols = [[0, 1, 2], ['a', 'b']] |
| 40 |
>>> tbl = etl.fromcolumns(cols, missing='NA') |
| 41 |
>>> tbl |
| 42 |
+----+------+ |
| 43 |
| f0 | f1 | |
| 44 |
+====+======+ |
| 45 |
| 0 | 'a' | |
| 46 |
+----+------+ |
| 47 |
| 1 | 'b' | |
| 48 |
+----+------+ |
| 49 |
| 2 | 'NA' | |
| 50 |
+----+------+ |
| 51 |
|
| 52 |
See also :func:`petl.io.json.fromdicts`. |
| 53 |
|
| 54 |
.. versionadded:: 1.1.0 |
| 55 |
|
| 56 |
""" |
| 57 |
|
| 58 |
return ColumnsView(cols, header=header, missing=missing) |
| 59 |
|
| 60 |
|
| 61 |
class ColumnsView(Table): |
| 62 |
|
| 63 |
def __init__(self, cols, header=None, missing=None): |
| 64 |
self.cols = cols |
| 65 |
self.header = header |
| 66 |
self.missing = missing |
| 67 |
|
| 68 |
def __iter__(self): |
| 69 |
return itercolumns(self.cols, self.header, self.missing) |
| 70 |
|
| 71 |
|
| 72 |
def itercolumns(cols, header, missing): |
| 73 |
if header is None: |
| 74 |
header = ['f%s' % i for i in range(len(cols))] |
| 75 |
yield tuple(header) |
| 76 |
for row in izip_longest(*cols, **dict(fillvalue=missing)): |
| 77 |
yield row |