code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
needs_closing = False
# convenience for working with sqlite3
if isinstance(dbo, string_types):
import sqlite3
dbo = sqlite3.connect(dbo)
needs_closing = True
try:
_todb(table, dbo, tablename, schema=schema, commit=commit,
truncate=False)
finally... | def appenddb(table, dbo, tablename, schema=None, commit=True) | Load data into an existing database table via a DB-API 2.0
connection or cursor. As :func:`petl.io.db.todb` except that the database
table will be appended, i.e., the new data will be inserted into the
table, and any existing rows will remain. | 4.062488 | 3.674285 | 1.105654 |
cols = OrderedDict()
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
for f in flds:
cols[f] = list()
for row in it:
for f, v in izip_longest(flds, row, fillvalue=missing):
if f in cols:
cols[f].append(v)
return cols | def columns(table, missing=None) | Construct a :class:`dict` mapping field names to lists of values. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]]
>>> cols = etl.columns(table)
>>> cols['foo']
['a', 'b', 'b']
>>> cols['bar']
[1, 2, 3]
See also :func:... | 2.953169 | 3.208403 | 0.920448 |
fct = dict()
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
indices = asindices(hdr, key)
assert len(indices) > 0, 'no key field selected'
getkey = operator.itemgetter(*indices)
for row in it:
kv = getkey(row)
if kv not in fct:
cols = ... | def facetcolumns(table, key, missing=None) | Like :func:`petl.util.materialise.columns` but stratified by values of the
given key field. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar', 'baz'],
... ['a', 1, True],
... ['b', 2, True],
... ['b', 3]]
>>> fc = etl.facetcolumns(ta... | 3.177962 | 3.594729 | 0.884061 |
_writepickle(table, source=source, mode='wb', protocol=protocol,
write_header=write_header) | def topickle(table, source=None, protocol=-1, write_header=True) | Write the table to a pickle file. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
>>> etl.topickle(table1, 'example.p')
>>> # look what it did
... table2 = etl.frompickle(... | 4.334139 | 6.512033 | 0.665559 |
_writepickle(table, source=source, mode='ab', protocol=protocol,
write_header=write_header) | def appendpickle(table, source=None, protocol=-1, write_header=False) | Append data to an existing pickle file. I.e.,
as :func:`petl.io.pickle.topickle` but the file is opened in append mode.
Note that no attempt is made to check that the fields or row lengths are
consistent with the existing data, the data rows from the table are simply
appended to the file. | 4.139475 | 6.143468 | 0.673801 |
return TeePickleView(table, source=source, protocol=protocol,
write_header=write_header) | def teepickle(table, source=None, protocol=-1, write_header=True) | Return a table that writes rows to a pickle file as they are iterated
over. | 3.925545 | 4.192108 | 0.936413 |
source = read_source_from_arg(source)
return JsonView(source, *args, **kwargs) | def fromjson(source, *args, **kwargs) | Extract data from a JSON file. The file must contain a JSON array as
the top level object, and each member of the array will be treated as a
row of data. E.g.::
>>> import petl as etl
>>> data = '''
... [{"foo": "a", "bar": 1},
... {"foo": "b", "bar": 2},
... {"foo": "c"... | 9.291181 | 21.76199 | 0.426945 |
return DictsView(dicts, header=header, sample=sample, missing=missing) | def fromdicts(dicts, header=None, sample=1000, missing=None) | View a sequence of Python :class:`dict` as a table. E.g.::
>>> import petl as etl
>>> dicts = [{"foo": "a", "bar": 1},
... {"foo": "b", "bar": 2},
... {"foo": "c", "bar": 2}]
>>> table1 = etl.fromdicts(dicts, header=['foo', 'bar'])
>>> table1
+-... | 5.030895 | 9.200877 | 0.546784 |
obj = list(_dicts(table))
_writejson(source, obj, prefix, suffix, *args, **kwargs) | def tojson(table, source=None, prefix=None, suffix=None, *args, **kwargs) | Write a table in JSON format, with rows output as JSON objects. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
>>> etl.tojson(table1, 'example.json', sort_keys=True)
>>> # check ... | 7.73622 | 12.401957 | 0.62379 |
if output_header:
obj = list(table)
else:
obj = list(data(table))
_writejson(source, obj, prefix, suffix, *args, **kwargs) | def tojsonarrays(table, source=None, prefix=None, suffix=None,
output_header=False, *args, **kwargs) | Write a table in JSON format, with rows output as JSON arrays. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
>>> etl.tojsonarrays(table1, 'example.json')
>>> # check what it did... | 4.582346 | 7.241315 | 0.632806 |
import numpy as np
it = iter(table)
peek, it = iterpeek(it, sample)
hdr = next(it)
flds = list(map(str, hdr))
dtype = construct_dtype(flds, peek, dtype)
# numpy is fussy about having tuples, need to make sure
it = (tuple(row) for row in it)
sa = np.fromiter(it, dtype=dtype, co... | def toarray(table, dtype=None, count=-1, sample=1000) | Load data from the given `table` into a
`numpy <http://www.numpy.org/>`_ structured array. E.g.::
>>> import petl as etl
>>> table = [('foo', 'bar', 'baz'),
... ('apples', 1, 2.5),
... ('oranges', 3, 4.4),
... ('pears', 7, .1)]
>>> a = etl.... | 5.608231 | 7.05303 | 0.795152 |
import numpy as np
return toarray(*args, **kwargs).view(np.recarray) | def torecarray(*args, **kwargs) | Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``. | 4.430295 | 2.974329 | 1.489511 |
import numpy as np
it = iter(vals)
if dtype is None:
peek, it = iterpeek(it, sample)
dtype = np.array(peek).dtype
a = np.fromiter(it, dtype=dtype, count=count)
return a | def valuestoarray(vals, dtype=None, count=-1, sample=1000) | Load values from a table column into a `numpy <http://www.numpy.org/>`_
array, e.g.::
>>> import petl as etl
>>> table = [('foo', 'bar', 'baz'),
... ('apples', 1, 2.5),
... ('oranges', 3, 4.4),
... ('pears', 7, .1)]
>>> table = etl.wrap(tab... | 3.805537 | 5.118118 | 0.743542 |
source = read_source_from_arg(source)
return XmlView(source, *args, **kwargs) | def fromxml(source, *args, **kwargs) | Extract data from an XML file. E.g.::
>>> import petl as etl
>>> # setup a file to demonstrate with
... d = '''<table>
... <tr>
... <td>foo</td><td>bar</td>
... </tr>
... <tr>
... <td>a</td><td>1</td>
... </tr>
... | 8.960412 | 16.145479 | 0.55498 |
# TODO don't read the data twice!
return convert(table, header(table), *args, **kwargs) | def convertall(table, *args, **kwargs) | Convenience function to convert all fields in the table using a common
function or mapping. See also :func:`convert`.
The ``where`` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
conversion should be applied on that row, el... | 13.233602 | 16.99457 | 0.778696 |
return convert(table, field, {a: b}, **kwargs) | def replace(table, field, a, b, **kwargs) | Convenience function to replace all occurrences of `a` with `b` under the
given field. See also :func:`convert`.
The ``where`` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
conversion should be applied on that row, else Fa... | 9.986567 | 10.513548 | 0.949876 |
return convertall(table, {a: b}, **kwargs) | def replaceall(table, a, b, **kwargs) | Convenience function to replace all instances of `a` with `b` under all
fields. See also :func:`convertall`.
The ``where`` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
conversion should be applied on that row, else False. | 13.277449 | 11.696178 | 1.135195 |
return convert(table, field, lambda v: value, **kwargs) | def update(table, field, value, **kwargs) | Convenience function to convert a field to a fixed value. Accepts the
``where`` keyword argument. See also :func:`convert`. | 12.653923 | 10.046694 | 1.259511 |
return convertall(table, numparser(strict), **kwargs) | def convertnumbers(table, strict=False, **kwargs) | Convenience function to convert all field values to numbers where
possible. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz', 'quux'],
... ['1', '3.0', '9+3j', 'aaa'],
... ['2', '1.3', '7+2j', None]]
>>> table2 = etl.convertnumbers(table1)... | 18.840839 | 31.201431 | 0.603845 |
conv = lambda v: fmt.format(v)
return convert(table, field, conv, **kwargs) | def format(table, field, fmt, **kwargs) | Convenience function to format all values in the given `field` using the
`fmt` format string.
The ``where`` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
conversion should be applied on that row, else False. | 5.665411 | 6.983341 | 0.811275 |
conv = lambda v: fmt.format(v)
return convertall(table, conv, **kwargs) | def formatall(table, fmt, **kwargs) | Convenience function to format all values in all fields using the
`fmt` format string.
The ``where`` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
conversion should be applied on that row, else False. | 6.917872 | 7.768019 | 0.890558 |
conv = lambda v: fmt % v
return convert(table, field, conv, **kwargs) | def interpolate(table, field, fmt, **kwargs) | Convenience function to interpolate all values in the given `field` using
the `fmt` string.
The ``where`` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
conversion should be applied on that row, else False. | 7.671781 | 8.603663 | 0.891688 |
conv = lambda v: fmt % v
return convertall(table, conv, **kwargs) | def interpolateall(table, fmt, **kwargs) | Convenience function to interpolate all values in all fields using
the `fmt` string.
The ``where`` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
conversion should be applied on that row, else False. | 8.395133 | 9.840335 | 0.853135 |
return SortView(table, key=key, reverse=reverse, buffersize=buffersize,
tempdir=tempdir, cache=cache) | def sort(table, key=None, reverse=False, buffersize=None, tempdir=None,
cache=True) | Sort the table. Field names or indices (from zero) can be used to specify
the key. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['C', 2],
... ['A', 9],
... ['A', 6],
... ['F', 1],
... ['D', ... | 3.189612 | 4.430291 | 0.719955 |
if key is None:
keyed_iterables = iterables
for element in heapq.merge(*keyed_iterables):
yield element
else:
keyed_iterables = [(_Keyed(key(obj), obj) for obj in iterable)
for iterable in iterables]
for element in heapq.merge(*keyed_i... | def _heapqmergesorted(key=None, *iterables) | Return a single iterator over the given iterables, sorted by the
given `key` function, assuming the input iterables are already sorted by
the same function. (I.e., the merge part of a general merge sort.) Uses
:func:`heapq.merge` for the underlying implementation. | 2.831947 | 2.869601 | 0.986878 |
if reverse:
op = max
else:
op = min
if key is not None:
opkwargs = {'key': key}
else:
opkwargs = dict()
# populate initial shortlist
# (remember some iterables might be empty)
iterators = list()
shortlist = list()
for iterable in iterables:
... | def _shortlistmergesorted(key=None, reverse=False, *iterables) | Return a single iterator over the given iterables, sorted by the
given `key` function, assuming the input iterables are already sorted by
the same function. (I.e., the merge part of a general merge sort.) Uses
:func:`min` (or :func:`max` if ``reverse=True``) for the underlying
implementation. | 2.788352 | 2.726825 | 1.022564 |
# determine the operator to use when comparing rows
if reverse and strict:
op = operator.lt
elif reverse and not strict:
op = operator.le
elif strict:
op = operator.gt
else:
op = operator.ge
it = iter(table)
flds = [text_type(f) for f in next(it)]
i... | def issorted(table, key=None, reverse=False, strict=False) | Return True if the table is ordered (i.e., sorted) by the given key. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['a', 1, True],
... ['b', 3, True],
... ['b', 2]]
>>> etl.issorted(table1, key='foo')
True
... | 2.739974 | 2.809054 | 0.975408 |
if dictionary is None:
dictionary = dict()
# setup
it, getkey, getvalue = _setup_lookup(table, key, value)
# build lookup dictionary
for row in it:
k = getkey(row)
v = getvalue(row)
if k in dictionary:
# work properly with shelve
l = di... | def lookup(table, key, value=None, dictionary=None) | Load a dictionary with data from the given table. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['b', 3]]
>>> lkp = etl.lookup(table1, 'foo', 'bar')
>>> lkp['a']
[1]
>>> l... | 3.539757 | 3.917043 | 0.903681 |
if dictionary is None:
dictionary = dict()
# setup
it, getkey, getvalue = _setup_lookup(table, key, value)
# build lookup dictionary
for row in it:
k = getkey(row)
if strict and k in dictionary:
raise DuplicateKeyError(k)
elif k not in dictionary:
... | def lookupone(table, key, value=None, dictionary=None, strict=False) | Load a dictionary with data from the given table, assuming there is
at most one value for each key. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['b', 3]]
>>> # if the specified key is not u... | 3.49812 | 4.073324 | 0.858788 |
if dictionary is None:
dictionary = dict()
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
keyindices = asindices(hdr, key)
assert len(keyindices) > 0, 'no key selected'
getkey = operator.itemgetter(*keyindices)
for row in it:
k = getkey(row)
... | def dictlookupone(table, key, dictionary=None, strict=False) | Load a dictionary with data from the given table, mapping to dicts,
assuming there is at most one row for each key. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['b', 3]]
>>> # if the specif... | 3.42129 | 3.832933 | 0.892604 |
if dictionary is None:
dictionary = dict()
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
keyindices = asindices(hdr, key)
assert len(keyindices) > 0, 'no key selected'
getkey = operator.itemgetter(*keyindices)
for row in it:
k = getkey(row)
... | def recordlookup(table, key, dictionary=None) | Load a dictionary with data from the given table, mapping to record objects. | 3.718594 | 3.51658 | 1.057446 |
return BcolzView(source, expression=expression, outcols=outcols,
limit=limit, skip=skip) | def frombcolz(source, expression=None, outcols=None, limit=None, skip=0) | Extract a table from a bcolz ctable, e.g.::
>>> import petl as etl
>>> import bcolz
>>> cols = [
... ['apples', 'oranges', 'pears'],
... [1, 3, 7],
... [2.5, 4.4, .1]
... ]
>>> names = ('foo', 'bar', 'baz')
>>> ctbl = bcolz.ctable(cols... | 3.608431 | 5.092095 | 0.708634 |
import bcolz
import numpy as np
it = iter(table)
peek, it = iterpeek(it, sample)
hdr = next(it)
# numpy is fussy about having tuples, need to make sure
it = (tuple(row) for row in it)
flds = list(map(text_type, hdr))
dtype = construct_dtype(flds, peek, dtype)
# create cta... | def tobcolz(table, dtype=None, sample=1000, **kwargs) | Load data into a bcolz ctable, e.g.::
>>> import petl as etl
>>> table = [('foo', 'bar', 'baz'),
... ('apples', 1, 2.5),
... ('oranges', 3, 4.4),
... ('pears', 7, .1)]
>>> ctbl = etl.tobcolz(table)
>>> ctbl
ctable((3,), [('foo',... | 3.90693 | 4.071793 | 0.959511 |
import bcolz
import numpy as np
if isinstance(obj, string_types):
ctbl = bcolz.open(obj, mode='a')
else:
assert hasattr(obj, 'append') and hasattr(obj, 'names'), \
'expected rootdir or ctable, found %r' % obj
ctbl = obj
# setup
dtype = ctbl.dtype
i... | def appendbcolz(table, obj, check_names=True) | Append data into a bcolz ctable. The `obj` argument can be either an
existing ctable or the name of a directory were an on-disk ctable is
stored.
.. versionadded:: 1.1.0 | 3.251575 | 3.121821 | 1.041563 |
return MeltView(table, key=key, variables=variables,
variablefield=variablefield,
valuefield=valuefield) | def melt(table, key=None, variables=None, variablefield='variable',
valuefield='value') | Reshape a table, melting fields into data. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'gender', 'age'],
... [1, 'F', 12],
... [2, 'M', 17],
... [3, 'M', 16]]
>>> table2 = etl.melt(table1, 'id')
>>> table2.lookall()
+-... | 3.288277 | 5.040175 | 0.652413 |
return PivotView(table, f1, f2, f3, aggfun, missing=missing,
presorted=presorted, buffersize=buffersize,
tempdir=tempdir, cache=cache) | def pivot(table, f1, f2, f3, aggfun, missing=None,
presorted=False, buffersize=None, tempdir=None, cache=True) | Construct a pivot table. E.g.::
>>> import petl as etl
>>> table1 = [['region', 'gender', 'style', 'units'],
... ['east', 'boy', 'tee', 12],
... ['east', 'boy', 'golf', 14],
... ['east', 'boy', 'fancy', 7],
... ['east', 'girl', 'te... | 1.94627 | 2.690331 | 0.723432 |
source = read_source_from_arg(source)
return TextView(source, header=header, encoding=encoding,
errors=errors, strip=strip) | def fromtext(source=None, encoding=None, errors='strict', strip=None,
header=('lines',)) | Extract a table from lines in the given text file. E.g.::
>>> import petl as etl
>>> # setup example file
... text = 'a,1\\nb,2\\nc,2\\n'
>>> with open('example.txt', 'w') as f:
... f.write(text)
...
12
>>> table1 = etl.fromtext('example.txt')
... | 5.511103 | 8.681862 | 0.634784 |
_writetext(table, source=source, mode='wb', encoding=encoding,
errors=errors, template=template, prologue=prologue,
epilogue=epilogue) | def totext(table, source=None, encoding=None, errors='strict', template=None,
prologue=None, epilogue=None) | Write the table to a text file. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
>>> prologue = '''{| class="wikitable"
... |-
... ! foo
... ! bar
... '''
... | 2.801955 | 3.784901 | 0.740298 |
assert template is not None, 'template is required'
return TeeTextView(table, source=source, encoding=encoding, errors=errors,
template=template, prologue=prologue, epilogue=epilogue) | def teetext(table, source=None, encoding=None, errors='strict', template=None,
prologue=None, epilogue=None) | Return a table that writes rows to a text file as they are iterated over. | 2.733316 | 2.878713 | 0.949492 |
# noqa
return ProblemsView(table, constraints=constraints, header=header) | def validate(table, constraints=None, header=None) | Validate a `table` against a set of `constraints` and/or an expected
`header`, e.g.::
>>> import petl as etl
>>> # define some validation constraints
... header = ('foo', 'bar', 'baz')
>>> constraints = [
... dict(name='foo_int', field='foo', test=int),
... d... | 15.481842 | 17.275604 | 0.896168 |
local_constraints = constraints or []
local_constraints = [dict(**c) for c in local_constraints]
local_constraints = [
c for c in local_constraints
if c.get('field') in flds or
not c.get('optional')
]
return local_constraints | def normalize_constraints(constraints, flds) | This method renders local constraints such that return value is:
* a list, not None
* a list of dicts
* a list of non-optional constraints or optional with defined field
.. note:: We use a new variable 'local_constraints' because the constraints
parameter may be a mutable collection... | 3.721468 | 2.812469 | 1.323203 |
# TODO don't read data twice (occurs if using natural key)
lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
return JoinView(left, right, lkey=lkey, rkey=rkey,
presorted=presorted, buffersize=buffersize, tempdir=tempdir,
cache=cache, lprefix=lprefix, rpr... | def join(left, right, key=None, lkey=None, rkey=None, presorted=False,
buffersize=None, tempdir=None, cache=True, lprefix=None, rprefix=None) | Perform an equi-join on the given tables. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'colour'],
... [1, 'blue'],
... [2, 'red'],
... [3, 'purple']]
>>> table2 = [['id', 'shape'],
... [1, 'circle'],
... ... | 3.505993 | 4.219221 | 0.830957 |
# TODO don't read data twice (occurs if using natural key)
lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
return JoinView(left, right, lkey=lkey, rkey=rkey,
presorted=presorted, leftouter=False, rightouter=True,
missing=missing, buffersize=buffersize,... | def rightjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
presorted=False, buffersize=None, tempdir=None, cache=True,
lprefix=None, rprefix=None) | Perform a right outer join on the given tables. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'colour'],
... [1, 'blue'],
... [2, 'red'],
... [3, 'purple']]
>>> table2 = [['id', 'shape'],
... [1, 'circle'],
...... | 3.627537 | 4.089162 | 0.88711 |
lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
return AntiJoinView(left=left, right=right, lkey=lkey, rkey=rkey,
presorted=presorted, buffersize=buffersize,
tempdir=tempdir, cache=cache) | def antijoin(left, right, key=None, lkey=None, rkey=None, presorted=False,
buffersize=None, tempdir=None, cache=True) | Return rows from the `left` table where the key value does not occur in
the `right` table. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'colour'],
... [0, 'black'],
... [1, 'blue'],
... [2, 'red'],
... [4, 'yellow'],
... | 2.260617 | 3.30812 | 0.683354 |
lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
return LookupJoinView(left, right, lkey, rkey, presorted=presorted,
missing=missing, buffersize=buffersize,
tempdir=tempdir, cache=cache,
lprefix=lprefix, rprefix=rprefix... | def lookupjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
presorted=False, buffersize=None, tempdir=None, cache=True,
lprefix=None, rprefix=None) | Perform a left join, but where the key is not unique in the right-hand
table, arbitrarily choose the first row and ignore others. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'color', 'cost'],
... [1, 'blue', 12],
... [2, 'red', 8],
... [3... | 2.196508 | 3.178069 | 0.691146 |
if key is None:
# first sort the table by the value field
if presorted:
tbl_sorted = table
else:
tbl_sorted = sort(table, value, buffersize=buffersize,
tempdir=tempdir, cache=cache)
# on the left, return the original table b... | def unjoin(table, value, key=None, autoincrement=(1, 1), presorted=False,
buffersize=None, tempdir=None, cache=True) | Split a table into two tables by reversing an inner join. E.g.::
>>> import petl as etl
>>> # join key is present in the table
... table1 = (('foo', 'bar', 'baz'),
... ('A', 1, 'apple'),
... ('B', 1, 'apple'),
... ('C', 2, 'orange'))
... | 4.645677 | 4.638439 | 1.00156 |
return RowReduceView(table, key, reducer, header=header,
presorted=presorted,
buffersize=buffersize, tempdir=tempdir, cache=cache) | def rowreduce(table, key, reducer, header=None, presorted=False,
buffersize=None, tempdir=None, cache=True) | Group rows under the given key then apply `reducer` to produce a single
output row for each input group of rows. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 3],
... ['a', 7],
... ['b', 2],
... ['b'... | 2.62105 | 3.506253 | 0.747536 |
s1 = cut(table, key, value)
s2 = distinct(s1)
s3 = aggregate(s2, key, len)
return s3 | def groupcountdistinctvalues(table, key, value) | Group by the `key` field then count the number of distinct values in the
`value` field. | 5.484594 | 6.73633 | 0.814181 |
def _reducer(k, rows):
return next(rows)
return rowreduce(table, key, reducer=_reducer, presorted=presorted,
buffersize=buffersize, tempdir=tempdir, cache=cache) | def groupselectfirst(table, key, presorted=False, buffersize=None,
tempdir=None, cache=True) | Group by the `key` field then return the first row within each group.
E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['C', 7, False],
... ['B', 2, False],
... ['C', 9, True]]
... | 4.045703 | 5.304965 | 0.762626 |
def _reducer(k, rows):
row = None
for row in rows:
pass
return row
return rowreduce(table, key, reducer=_reducer, presorted=presorted,
buffersize=buffersize, tempdir=tempdir, cache=cache) | def groupselectlast(table, key, presorted=False, buffersize=None,
tempdir=None, cache=True) | Group by the `key` field then return the last row within each group.
E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['C', 7, False],
... ['B', 2, False],
... ['C', 9, True]]
>... | 3.450268 | 4.576968 | 0.753833 |
return groupselectfirst(sort(table, value, reverse=False), key,
presorted=presorted, buffersize=buffersize,
tempdir=tempdir, cache=cache) | def groupselectmin(table, key, value, presorted=False, buffersize=None,
tempdir=None, cache=True) | Group by the `key` field then return the row with the minimum of the
`value` field within each group. N.B., will only return one row for each
group, even if multiple rows have the same (minimum) value. | 3.939404 | 4.569053 | 0.862193 |
return MergeDuplicatesView(table, key, missing=missing, presorted=presorted,
buffersize=buffersize, tempdir=tempdir,
cache=cache) | def mergeduplicates(table, key, missing=None, presorted=False, buffersize=None,
tempdir=None, cache=True) | Merge duplicate rows under the given key. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['A', 1, 2.7],
... ['B', 2, None],
... ['D', 3, 9.4],
... ['B', None, 7.8],
... ['E', None, 42.],
... | 2.617121 | 4.390842 | 0.596041 |
assert 'key' in kwargs, 'keyword argument "key" is required'
key = kwargs['key']
t1 = mergesort(*tables, **kwargs)
t2 = mergeduplicates(t1, key=key, presorted=True)
return t2 | def merge(*tables, **kwargs) | Convenience function to combine multiple tables (via
:func:`petl.transform.sorts.mergesort`) then combine duplicate rows by
merging under the given key (via
:func:`petl.transform.reductions.mergeduplicates`). E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ... | 5.252374 | 4.408922 | 1.191306 |
return FoldView(table, key, f, value=value, presorted=presorted,
buffersize=buffersize, tempdir=tempdir, cache=cache) | def fold(table, key, f, value=None, presorted=False, buffersize=None,
tempdir=None, cache=True) | Reduce rows recursively via the Python standard :func:`reduce` function.
E.g.::
>>> import petl as etl
>>> table1 = [['id', 'count'],
... [1, 3],
... [1, 5],
... [2, 4],
... [2, 8]]
>>> import operator
>>> table... | 2.510911 | 3.695757 | 0.679404 |
return TextIndexView(index_or_dirname, indexname=indexname,
docnum_field=docnum_field) | def fromtextindex(index_or_dirname, indexname=None, docnum_field=None) | Extract all documents from a Whoosh index. E.g.::
>>> import petl as etl
>>> import os
>>> # set up an index and load some documents via the Whoosh API
... from whoosh.index import create_in
>>> from whoosh.fields import *
>>> schema = Schema(title=TEXT(stored=True), pat... | 3.353411 | 5.554796 | 0.603696 |
import whoosh.index
import whoosh.writing
# deal with polymorphic argument
if isinstance(index_or_dirname, string_types):
dirname = index_or_dirname
index = whoosh.index.create_in(dirname, schema,
indexname=indexname)
needs_closing = T... | def totextindex(table, index_or_dirname, schema=None, indexname=None,
merge=False, optimize=False) | Load all rows from `table` into a Whoosh index. N.B., this will clear any
existing data in the index before loading. E.g.::
>>> import petl as etl
>>> import datetime
>>> import os
>>> # here is the table we want to load into an index
... table = (('f0', 'f1', 'f2', 'f3', 'f... | 2.919772 | 3.130653 | 0.93264 |
import whoosh.index
# deal with polymorphic argument
if isinstance(index_or_dirname, string_types):
dirname = index_or_dirname
index = whoosh.index.open_dir(dirname, indexname=indexname,
readonly=False)
needs_closing = True
elif isinsta... | def appendtextindex(table, index_or_dirname, indexname=None, merge=True,
optimize=False) | Load all rows from `table` into a Whoosh index, adding them to any existing
data in the index.
Keyword arguments:
table
A table container with the data to be loaded.
index_or_dirname
Either an instance of `whoosh.index.Index` or a string containing the
directory path where the ... | 2.637564 | 2.891928 | 0.912043 |
return SearchTextIndexView(index_or_dirname, query, limit=limit,
indexname=indexname, docnum_field=docnum_field,
score_field=score_field, fieldboosts=fieldboosts,
search_kwargs=search_kwargs) | def searchtextindex(index_or_dirname, query, limit=10, indexname=None,
docnum_field=None, score_field=None, fieldboosts=None,
search_kwargs=None) | Search a Whoosh index using a query. E.g.::
>>> import petl as etl
>>> import os
>>> # set up an index and load some documents via the Whoosh API
... from whoosh.index import create_in
>>> from whoosh.fields import *
>>> schema = Schema(title=TEXT(stored=True), path=ID(s... | 1.83547 | 2.512743 | 0.730465 |
return SearchTextIndexView(index_or_dirname, query, pagenum=pagenum,
pagelen=pagelen, indexname=indexname,
docnum_field=docnum_field,
score_field=score_field, fieldboosts=fieldboosts,
se... | def searchtextindexpage(index_or_dirname, query, pagenum, pagelen=10,
indexname=None, docnum_field=None, score_field=None,
fieldboosts=None, search_kwargs=None) | Search an index using a query, returning a result page.
Keyword arguments:
index_or_dirname
Either an instance of `whoosh.index.Index` or a string containing the
directory path where the index is to be stored.
query
Either a string or an instance of `whoosh.query.Query`. If a strin... | 1.751624 | 2.165013 | 0.809059 |
lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
return HashJoinView(left, right, lkey=lkey, rkey=rkey, cache=cache,
lprefix=lprefix, rprefix=rprefix) | def hashjoin(left, right, key=None, lkey=None, rkey=None, cache=True,
lprefix=None, rprefix=None) | Alternative implementation of :func:`petl.transform.joins.join`, where
the join is executed by constructing an in-memory lookup for the right
hand table, then iterating over rows from the left hand table.
May be faster and/or more resource efficient where the right table is small
and the left table... | 2.417028 | 3.003709 | 0.804681 |
lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
return HashLeftJoinView(left, right, lkey, rkey, missing=missing,
cache=cache, lprefix=lprefix, rprefix=rprefix) | def hashleftjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
cache=True, lprefix=None, rprefix=None) | Alternative implementation of :func:`petl.transform.joins.leftjoin`,
where the join is executed by constructing an in-memory lookup for the
right hand table, then iterating over rows from the left hand table.
May be faster and/or more resource efficient where the right table is small
and the left t... | 2.509444 | 3.13737 | 0.799856 |
lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
return HashRightJoinView(left, right, lkey, rkey, missing=missing,
cache=cache, lprefix=lprefix, rprefix=rprefix) | def hashrightjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
cache=True, lprefix=None, rprefix=None) | Alternative implementation of :func:`petl.transform.joins.rightjoin`,
where the join is executed by constructing an in-memory lookup for the
left hand table, then iterating over rows from the right hand table.
May be faster and/or more resource efficient where the left table is small
and the right ... | 2.616418 | 3.214598 | 0.813918 |
lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
return HashAntiJoinView(left, right, lkey, rkey) | def hashantijoin(left, right, key=None, lkey=None, rkey=None) | Alternative implementation of :func:`petl.transform.joins.antijoin`,
where the join is executed by constructing an in-memory set for all keys
found in the right hand table, then iterating over rows from the left
hand table.
May be faster and/or more resource efficient where the right table is small... | 3.525857 | 4.335847 | 0.813187 |
lkey, rkey = keys_from_args(left, right, key, lkey, rkey)
return HashLookupJoinView(left, right, lkey, rkey, missing=missing,
lprefix=lprefix, rprefix=rprefix) | def hashlookupjoin(left, right, key=None, lkey=None, rkey=None, missing=None,
lprefix=None, rprefix=None) | Alternative implementation of :func:`petl.transform.joins.lookupjoin`,
where the join is executed by constructing an in-memory lookup for the
right hand table, then iterating over rows from the left hand table.
May be faster and/or more resource efficient where the right table is small
and the left tab... | 2.586198 | 3.342292 | 0.77378 |
return XLSView(filename, sheet=sheet, use_view=use_view) | def fromxls(filename, sheet=None, use_view=True) | Extract a table from a sheet in an Excel .xls file.
Sheet is identified by its name or index number.
N.B., the sheet name is case sensitive. | 3.636334 | 4.971703 | 0.731406 |
import xlwt
if encoding is None:
encoding = locale.getpreferredencoding()
wb = xlwt.Workbook(encoding=encoding, style_compression=style_compression)
ws = wb.add_sheet(sheet)
if styles is None:
# simple version, don't worry about styles
for r, row in enumerate(tbl):
... | def toxls(tbl, filename, sheet, encoding=None, style_compression=0,
styles=None) | Write a table to a new Excel .xls file. | 2.330978 | 2.349209 | 0.99224 |
flds = list(map(text_type, hdr))
indices = list()
if not isinstance(spec, (list, tuple)):
spec = (spec,)
for s in spec:
# spec could be a field index (takes priority)
if isinstance(s, int) and s < len(hdr):
indices.append(s) # index fields from 0
# spec... | def asindices(hdr, spec) | Convert the given field `spec` into a list of field indices. | 4.070918 | 3.728864 | 1.091731 |
prog = re.compile('\{([^}]+)\}')
def repl(matchobj):
return "rec['%s']" % matchobj.group(1)
return eval("lambda rec: " + prog.sub(repl, s)) | def expr(s) | Construct a function operating on a table record.
The expression string is converted into a lambda function by prepending
the string with ``'lambda rec: '``, then replacing anything enclosed in
curly braces (e.g., ``"{foo}"``) with a lookup on the record (e.g.,
``"rec['foo']"``), then finally calling :... | 5.154497 | 3.603914 | 1.43025 |
it = iter(table)
hdr = next(it)
flds = list(map(text_type, hdr))
# wrap rows as records
it = (Record(row, flds) for row in it)
# determine key function
if callable(key):
getkey = key
native_key = True
else:
kindices = asindices(hdr, key)
getkey = co... | def rowgroupby(table, key, value=None) | Convenient adapter for :func:`itertools.groupby`. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['a', 1, True],
... ['b', 3, True],
... ['b', 2]]
>>> # group entire rows
... for key, group in etl.rowgroupby(t... | 2.962157 | 3.086702 | 0.959651 |
source = read_source_from_arg(source)
csvargs.setdefault('dialect', 'excel')
return fromcsv_impl(source=source, encoding=encoding, errors=errors,
header=header, **csvargs) | def fromcsv(source=None, encoding=None, errors='strict', header=None,
**csvargs) | Extract a table from a delimited file. E.g.::
>>> import petl as etl
>>> import csv
>>> # set up a CSV file to demonstrate with
... table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
>>> with open('example.cs... | 3.293433 | 5.029729 | 0.654793 |
csvargs.setdefault('dialect', 'excel-tab')
return fromcsv(source, encoding=encoding, errors=errors, **csvargs) | def fromtsv(source=None, encoding=None, errors='strict', header=None,
**csvargs) | Convenience function, as :func:`petl.io.csv.fromcsv` but with different
default dialect (tab delimited). | 2.969149 | 3.350176 | 0.886267 |
source = write_source_from_arg(source)
csvargs.setdefault('dialect', 'excel')
tocsv_impl(table, source=source, encoding=encoding, errors=errors,
write_header=write_header, **csvargs) | def tocsv(table, source=None, encoding=None, errors='strict', write_header=True,
**csvargs) | Write the table to a CSV file. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
>>> etl.tocsv(table1, 'example.csv')
>>> # look what it did
... print(open('example.csv').re... | 3.469223 | 5.002425 | 0.693508 |
source = write_source_from_arg(source)
csvargs.setdefault('dialect', 'excel')
appendcsv_impl(table, source=source, encoding=encoding, errors=errors,
write_header=write_header, **csvargs) | def appendcsv(table, source=None, encoding=None, errors='strict',
write_header=False, **csvargs) | Append data rows to an existing CSV file. As :func:`petl.io.csv.tocsv`
but the file is opened in append mode and the table header is not written by
default.
Note that no attempt is made to check that the fields or row lengths are
consistent with the existing data, the data rows from the table are simpl... | 3.384406 | 4.349571 | 0.778101 |
csvargs.setdefault('dialect', 'excel-tab')
return tocsv(table, source=source, encoding=encoding, errors=errors,
write_header=write_header, **csvargs) | def totsv(table, source=None, encoding=None, errors='strict',
write_header=True, **csvargs) | Convenience function, as :func:`petl.io.csv.tocsv` but with different
default dialect (tab delimited). | 2.271929 | 2.419671 | 0.938941 |
csvargs.setdefault('dialect', 'excel-tab')
return appendcsv(table, source=source, encoding=encoding, errors=errors,
write_header=write_header, **csvargs) | def appendtsv(table, source=None, encoding=None, errors='strict',
write_header=False, **csvargs) | Convenience function, as :func:`petl.io.csv.appendcsv` but with different
default dialect (tab delimited). | 2.243729 | 2.44936 | 0.916047 |
source = write_source_from_arg(source)
csvargs.setdefault('dialect', 'excel')
return teecsv_impl(table, source=source, encoding=encoding,
errors=errors, write_header=write_header,
**csvargs) | def teecsv(table, source=None, encoding=None, errors='strict', write_header=True,
**csvargs) | Returns a table that writes rows to a CSV file as they are iterated over. | 3.317238 | 3.351697 | 0.989719 |
csvargs.setdefault('dialect', 'excel-tab')
return teecsv(table, source=source, encoding=encoding, errors=errors,
write_header=write_header, **csvargs) | def teetsv(table, source=None, encoding=None, errors='strict', write_header=True,
**csvargs) | Convenience function, as :func:`petl.io.csv.teecsv` but with different
default dialect (tab delimited). | 2.669908 | 2.387051 | 1.118496 |
return CaptureView(table, field, pattern,
newfields=newfields,
include_original=include_original,
flags=flags,
fill=fill) | def capture(table, field, pattern, newfields=None, include_original=False,
flags=0, fill=None) | Add one or more new fields with values captured from an existing field
searched via a regular expression. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'variable', 'value'],
... ['1', 'A1', '12'],
... ['2', 'A2', '15'],
... ['3', 'B1', '18'... | 2.868335 | 5.046776 | 0.56835 |
return SplitView(table, field, pattern, newfields, include_original,
maxsplit, flags) | def split(table, field, pattern, newfields=None, include_original=False,
maxsplit=0, flags=0) | Add one or more new fields with values generated by splitting an
existing value around occurrences of a regular expression. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'variable', 'value'],
... ['1', 'parad1', '12'],
... ['2', 'parad2', '15'],
... ... | 3.828207 | 7.005208 | 0.54648 |
prog = re.compile(pattern, flags)
conv = lambda v: prog.sub(repl, v, count=count)
return convert(table, field, conv) | def sub(table, field, pattern, repl, count=0, flags=0) | Convenience function to convert values under the given field using a
regular expression substitution. See also :func:`re.sub`. | 4.049287 | 3.529737 | 1.147193 |
if len(args) == 1:
field = None
pattern = args[0]
elif len(args) == 2:
field = args[0]
pattern = args[1]
else:
raise ArgumentError('expected 1 or 2 positional arguments')
return SearchView(table, pattern, field=field, **kwargs) | def search(table, *args, **kwargs) | Perform a regular expression search, returning rows that match a given
pattern, either anywhere in the row or within a specific field. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['orange', 12, 'oranges are nice fruit'],
... ['mango', 4... | 2.898463 | 2.841654 | 1.019992 |
return search(table, *args, complement=True, **kwargs) | def searchcomplement(table, *args, **kwargs) | Perform a regular expression search, returning rows that **do not**
match a given pattern, either anywhere in the row or within a specific
field. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['orange', 12, 'oranges are nice fruit'],
... ... | 7.32421 | 16.98101 | 0.431318 |
return ColumnsView(cols, header=header, missing=missing) | def fromcolumns(cols, header=None, missing=None) | View a sequence of columns as a table, e.g.::
>>> import petl as etl
>>> cols = [[0, 1, 2], ['a', 'b', 'c']]
>>> tbl = etl.fromcolumns(cols)
>>> tbl
+----+-----+
| f0 | f1 |
+====+=====+
| 0 | 'a' |
+----+-----+
| 1 | 'b' |
+---... | 8.517364 | 17.467209 | 0.48762 |
# support passing a single list or tuple of fields
if len(args) == 1 and isinstance(args[0], (list, tuple)):
args = args[0]
return CutView(table, args, **kwargs) | def cut(table, *args, **kwargs) | Choose and/or re-order fields. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['A', 1, 2.7],
... ['B', 2, 3.4],
... ['B', 3, 7.8],
... ['D', 42, 9.0],
... ['E', 12]]
>>> table2 = et... | 4.394819 | 5.268387 | 0.834187 |
return AddFieldView(table, field, value=value, index=index,
missing=missing) | def addfield(table, field, value=None, index=None, missing=None) | Add a field with a fixed or calculated value. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['M', 12],
... ['F', 34],
... ['-', 56]]
>>> # using a fixed value
... table2 = etl.addfield(table1, 'baz', 42)
>>>... | 5.645075 | 8.106971 | 0.696324 |
return AddRowNumbersView(table, start, step, field) | def addrownumbers(table, start=1, step=1, field='row') | Add a field of row numbers. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['A', 9],
... ['C', 2],
... ['F', 1]]
>>> table2 = etl.addrownumbers(table1)
>>> table2
+-----+-----+-----+
| row | foo | bar... | 9.201872 | 15.159793 | 0.606992 |
return AddColumnView(table, field, col, index=index, missing=missing) | def addcolumn(table, field, col, index=None, missing=None) | Add a column of data to the table. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['A', 1],
... ['B', 2]]
>>> col = [True, False]
>>> table2 = etl.addcolumn(table1, 'baz', col)
>>> table2
+-----+-----+-------+
... | 4.974385 | 8.666939 | 0.573949 |
s = set()
for v in values(table, field):
try:
s.add(type(v).__name__)
except IndexError:
pass # ignore short rows
return s | def typeset(table, field) | Return a set containing all Python types found for values in the given
field. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar', 'baz'],
... ['A', 1, '2'],
... ['B', u'2', '3.4'],
... [u'B', u'3', '7.8', True],
... ['D', u'x... | 7.061031 | 9.403749 | 0.750874 |
t1h = set(header(t1))
t2h = set(header(t2))
return t2h - t1h, t1h - t2h | def diffheaders(t1, t2) | Return the difference between the headers of the two tables as a pair of
sets. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['a', 1, .3]]
>>> table2 = [['baz', 'bar', 'quux'],
... ['a', 1, .3]]
>>> add, sub = etl.diffhead... | 3.237124 | 4.38946 | 0.737477 |
t1v = set(values(t1, f))
t2v = set(values(t2, f))
return t2v - t1v, t1v - t2v | def diffvalues(t1, t2, f) | Return the difference between the values under the given field in the two
tables, e.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 3]]
>>> table2 = [['bar', 'foo'],
... [1, 'a'],
... [... | 3.024529 | 4.175059 | 0.724428 |
missing = kwargs.get('missing', None)
default = kwargs.get('default', None)
def _coalesce(row):
for f in fields:
v = row[f]
if v is not missing:
return v
return default
return _coalesce | def coalesce(*fields, **kwargs) | Return a function which accepts a row and returns the first non-missing
value from the specified fields. Intended for use with
:func:`petl.transform.basics.addfield`. | 2.42557 | 2.330233 | 1.040913 |
def parser(value):
try:
return datetime.datetime.strptime(value.strip(), fmt)
except Exception as e:
if strict:
raise e
else:
return value
return parser | def datetimeparser(fmt, strict=True) | Return a function to parse strings as :class:`datetime.datetime` objects
using a given format. E.g.::
>>> from petl import datetimeparser
>>> isodatetime = datetimeparser('%Y-%m-%dT%H:%M:%S')
>>> isodatetime('2002-12-25T00:00:00')
datetime.datetime(2002, 12, 25, 0, 0)
>>> tr... | 2.880525 | 3.27645 | 0.87916 |
def parser(value):
try:
return datetime.datetime.strptime(value.strip(), fmt).date()
except Exception as e:
if strict:
raise e
else:
return value
return parser | def dateparser(fmt, strict=True) | Return a function to parse strings as :class:`datetime.date` objects
using a given format. E.g.::
>>> from petl import dateparser
>>> isodate = dateparser('%Y-%m-%d')
>>> isodate('2002-12-25')
datetime.date(2002, 12, 25)
>>> try:
... isodate('2002-02-30')
... | 3.003235 | 3.321364 | 0.904217 |
def parser(value):
try:
return datetime.datetime.strptime(value.strip(), fmt).time()
except Exception as e:
if strict:
raise e
else:
return value
return parser | def timeparser(fmt, strict=True) | Return a function to parse strings as :class:`datetime.time` objects
using a given format. E.g.::
>>> from petl import timeparser
>>> isotime = timeparser('%H:%M:%S')
>>> isotime('00:00:00')
datetime.time(0, 0)
>>> isotime('13:00:00')
datetime.time(13, 0)
>>>... | 3.074619 | 3.370998 | 0.91208 |
if not case_sensitive:
true_strings = [s.lower() for s in true_strings]
false_strings = [s.lower() for s in false_strings]
def parser(value):
value = value.strip()
if not case_sensitive:
value = value.lower()
if value in true_strings:
return... | def boolparser(true_strings=('true', 't', 'yes', 'y', '1'),
false_strings=('false', 'f', 'no', 'n', '0'),
case_sensitive=False,
strict=True) | Return a function to parse strings as :class:`bool` objects using a
given set of string representations for `True` and `False`. E.g.::
>>> from petl import boolparser
>>> mybool = boolparser(true_strings=['yes', 'y'], false_strings=['no', 'n'])
>>> mybool('y')
True
>>> myboo... | 1.85796 | 1.897398 | 0.979214 |
def f(v):
try:
return int(v)
except (ValueError, TypeError):
pass
try:
return long(v)
except (ValueError, TypeError):
pass
try:
return float(v)
except (ValueError, TypeError):
pass
t... | def numparser(strict=False) | Return a function that will attempt to parse the value as a number,
trying :func:`int`, :func:`long`, :func:`float` and :func:`complex` in
that order. If all fail, return the value as-is, unless ``strict=True``,
in which case raise the underlying exception. | 2.077306 | 1.66331 | 1.248899 |
return ProgressView(table, batchsize, prefix, out) | def progress(table, batchsize=1000, prefix="", out=sys.stderr) | Report progress on rows passing through. E.g.::
>>> import petl as etl
>>> table = etl.dummytable(100000)
>>> table.progress(10000).tocsv('example.csv')
10000 rows in 0.13s (78363 row/s); batch in 0.13s (78363 row/s)
20000 rows in 0.22s (91679 row/s); batch in 0.09s (110448 row/... | 10.517169 | 19.193533 | 0.547954 |
return ComplementView(a, b, presorted=presorted, buffersize=buffersize,
tempdir=tempdir, cache=cache, strict=strict) | def complement(a, b, presorted=False, buffersize=None, tempdir=None,
cache=True, strict=False) | Return rows in `a` that are not in `b`. E.g.::
>>> import petl as etl
>>> a = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['C', 7, False],
... ['B', 2, False],
... ['C', 9, True]]
>>> b = [['x', 'y', 'z'],
... ['B', 2, False],... | 2.709136 | 3.76983 | 0.718636 |
# TODO possible with only one pass?
ha = header(a)
hb = header(b)
assert set(ha) == set(hb), 'both tables must have the same set of fields'
# make sure fields are in the same order
bv = cut(b, *ha)
return complement(a, bv, buffersize=buffersize, tempdir=tempdir,
... | def recordcomplement(a, b, buffersize=None, tempdir=None, cache=True,
strict=False) | Find records in `a` that are not in `b`. E.g.::
>>> import petl as etl
>>> a = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['C', 7, False],
... ['B', 2, False],
... ['C', 9, True]]
>>> b = [['bar', 'foo', 'baz'],
... [2, 'B', ... | 5.926434 | 5.523671 | 1.072916 |
if not presorted:
a = sort(a)
b = sort(b)
added = complement(b, a, presorted=True, buffersize=buffersize,
tempdir=tempdir, cache=cache, strict=strict)
subtracted = complement(a, b, presorted=True, buffersize=buffersize,
tempdir=tempdir... | def diff(a, b, presorted=False, buffersize=None, tempdir=None, cache=True,
strict=False) | Find the difference between rows in two tables. Returns a pair of tables.
E.g.::
>>> import petl as etl
>>> a = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['C', 7, False],
... ['B', 2, False],
... ['C', 9, True]]
>>> b = [['x', 'y', '... | 2.000455 | 1.966433 | 1.017302 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.