| 1 |
from __future__ import absolute_import, print_function, division |
| 2 |
|
| 3 |
|
| 4 |
from petl.compat import next, integer_types, string_types, text_type |
| 5 |
|
| 6 |
|
| 7 |
import petl.config as config |
| 8 |
from petl.errors import ArgumentError, FieldSelectionError |
| 9 |
from petl.util.base import Table, expr, fieldnames, Record |
| 10 |
from petl.util.parsers import numparser |
| 11 |
|
| 12 |
|
| 13 |
def convert(table, *args, **kwargs): |
| 14 |
"""Transform values under one or more fields via arbitrary functions, method |
| 15 |
invocations or dictionary translations. E.g.:: |
| 16 |
|
| 17 |
>>> import petl as etl |
| 18 |
>>> table1 = [['foo', 'bar', 'baz'], |
| 19 |
... ['A', '2.4', 12], |
| 20 |
... ['B', '5.7', 34], |
| 21 |
... ['C', '1.2', 56]] |
| 22 |
>>> # using a built-in function: |
| 23 |
... table2 = etl.convert(table1, 'bar', float) |
| 24 |
>>> table2 |
| 25 |
+-----+-----+-----+ |
| 26 |
| foo | bar | baz | |
| 27 |
+=====+=====+=====+ |
| 28 |
| 'A' | 2.4 | 12 | |
| 29 |
+-----+-----+-----+ |
| 30 |
| 'B' | 5.7 | 34 | |
| 31 |
+-----+-----+-----+ |
| 32 |
| 'C' | 1.2 | 56 | |
| 33 |
+-----+-----+-----+ |
| 34 |
|
| 35 |
>>> # using a lambda function:: |
| 36 |
... table3 = etl.convert(table1, 'baz', lambda v: v*2) |
| 37 |
>>> table3 |
| 38 |
+-----+-------+-----+ |
| 39 |
| foo | bar | baz | |
| 40 |
+=====+=======+=====+ |
| 41 |
| 'A' | '2.4' | 24 | |
| 42 |
+-----+-------+-----+ |
| 43 |
| 'B' | '5.7' | 68 | |
| 44 |
+-----+-------+-----+ |
| 45 |
| 'C' | '1.2' | 112 | |
| 46 |
+-----+-------+-----+ |
| 47 |
|
| 48 |
>>> # a method of the data value can also be invoked by passing |
| 49 |
... # the method name |
| 50 |
... table4 = etl.convert(table1, 'foo', 'lower') |
| 51 |
>>> table4 |
| 52 |
+-----+-------+-----+ |
| 53 |
| foo | bar | baz | |
| 54 |
+=====+=======+=====+ |
| 55 |
| 'a' | '2.4' | 12 | |
| 56 |
+-----+-------+-----+ |
| 57 |
| 'b' | '5.7' | 34 | |
| 58 |
+-----+-------+-----+ |
| 59 |
| 'c' | '1.2' | 56 | |
| 60 |
+-----+-------+-----+ |
| 61 |
|
| 62 |
>>> # arguments to the method invocation can also be given |
| 63 |
... table5 = etl.convert(table1, 'foo', 'replace', 'A', 'AA') |
| 64 |
>>> table5 |
| 65 |
+------+-------+-----+ |
| 66 |
| foo | bar | baz | |
| 67 |
+======+=======+=====+ |
| 68 |
| 'AA' | '2.4' | 12 | |
| 69 |
+------+-------+-----+ |
| 70 |
| 'B' | '5.7' | 34 | |
| 71 |
+------+-------+-----+ |
| 72 |
| 'C' | '1.2' | 56 | |
| 73 |
+------+-------+-----+ |
| 74 |
|
| 75 |
>>> # values can also be translated via a dictionary |
| 76 |
... table7 = etl.convert(table1, 'foo', {'A': 'Z', 'B': 'Y'}) |
| 77 |
>>> table7 |
| 78 |
+-----+-------+-----+ |
| 79 |
| foo | bar | baz | |
| 80 |
+=====+=======+=====+ |
| 81 |
| 'Z' | '2.4' | 12 | |
| 82 |
+-----+-------+-----+ |
| 83 |
| 'Y' | '5.7' | 34 | |
| 84 |
+-----+-------+-----+ |
| 85 |
| 'C' | '1.2' | 56 | |
| 86 |
+-----+-------+-----+ |
| 87 |
|
| 88 |
>>> # the same conversion can be applied to multiple fields |
| 89 |
... table8 = etl.convert(table1, ('foo', 'bar', 'baz'), str) |
| 90 |
>>> table8 |
| 91 |
+-----+-------+------+ |
| 92 |
| foo | bar | baz | |
| 93 |
+=====+=======+======+ |
| 94 |
| 'A' | '2.4' | '12' | |
| 95 |
+-----+-------+------+ |
| 96 |
| 'B' | '5.7' | '34' | |
| 97 |
+-----+-------+------+ |
| 98 |
| 'C' | '1.2' | '56' | |
| 99 |
+-----+-------+------+ |
| 100 |
|
| 101 |
>>> # multiple conversions can be specified at the same time |
| 102 |
... table9 = etl.convert(table1, {'foo': 'lower', |
| 103 |
... 'bar': float, |
| 104 |
... 'baz': lambda v: v * 2}) |
| 105 |
>>> table9 |
| 106 |
+-----+-----+-----+ |
| 107 |
| foo | bar | baz | |
| 108 |
+=====+=====+=====+ |
| 109 |
| 'a' | 2.4 | 24 | |
| 110 |
+-----+-----+-----+ |
| 111 |
| 'b' | 5.7 | 68 | |
| 112 |
+-----+-----+-----+ |
| 113 |
| 'c' | 1.2 | 112 | |
| 114 |
+-----+-----+-----+ |
| 115 |
|
| 116 |
>>> # ...or alternatively via a list |
| 117 |
... table10 = etl.convert(table1, ['lower', float, lambda v: v*2]) |
| 118 |
>>> table10 |
| 119 |
+-----+-----+-----+ |
| 120 |
| foo | bar | baz | |
| 121 |
+=====+=====+=====+ |
| 122 |
| 'a' | 2.4 | 24 | |
| 123 |
+-----+-----+-----+ |
| 124 |
| 'b' | 5.7 | 68 | |
| 125 |
+-----+-----+-----+ |
| 126 |
| 'c' | 1.2 | 112 | |
| 127 |
+-----+-----+-----+ |
| 128 |
|
| 129 |
>>> # conversion can be conditional |
| 130 |
... table11 = etl.convert(table1, 'baz', lambda v: v * 2, |
| 131 |
... where=lambda r: r.foo == 'B') |
| 132 |
>>> table11 |
| 133 |
+-----+-------+-----+ |
| 134 |
| foo | bar | baz | |
| 135 |
+=====+=======+=====+ |
| 136 |
| 'A' | '2.4' | 12 | |
| 137 |
+-----+-------+-----+ |
| 138 |
| 'B' | '5.7' | 68 | |
| 139 |
+-----+-------+-----+ |
| 140 |
| 'C' | '1.2' | 56 | |
| 141 |
+-----+-------+-----+ |
| 142 |
|
| 143 |
>>> # conversion can access other values from the same row |
| 144 |
... table12 = etl.convert(table1, 'baz', |
| 145 |
... lambda v, row: v * float(row.bar), |
| 146 |
... pass_row=True) |
| 147 |
>>> table12 |
| 148 |
+-----+-------+--------------------+ |
| 149 |
| foo | bar | baz | |
| 150 |
+=====+=======+====================+ |
| 151 |
| 'A' | '2.4' | 28.799999999999997 | |
| 152 |
+-----+-------+--------------------+ |
| 153 |
| 'B' | '5.7' | 193.8 | |
| 154 |
+-----+-------+--------------------+ |
| 155 |
| 'C' | '1.2' | 67.2 | |
| 156 |
+-----+-------+--------------------+ |
| 157 |
>>> # conversion can use a custom function |
| 158 |
>>> def my_func(val, row): |
| 159 |
... return float(row.bar) + row.baz |
| 160 |
... |
| 161 |
>>> table13 = etl.convert(table1, 'foo', my_func, pass_row=True) |
| 162 |
>>> table13 |
| 163 |
+------+-------+-----+ |
| 164 |
| foo | bar | baz | |
| 165 |
+======+=======+=====+ |
| 166 |
| 14.4 | '2.4' | 12 | |
| 167 |
+------+-------+-----+ |
| 168 |
| 39.7 | '5.7' | 34 | |
| 169 |
+------+-------+-----+ |
| 170 |
| 57.2 | '1.2' | 56 | |
| 171 |
+------+-------+-----+ |
| 172 |
|
| 173 |
Note that either field names or indexes can be given. |
| 174 |
|
| 175 |
The ``where`` keyword argument can be given with a callable or expression |
| 176 |
which is evaluated on each row and which should return True if the |
| 177 |
conversion should be applied on that row, else False. |
| 178 |
|
| 179 |
The ``pass_row`` keyword argument can be given, which if True will mean |
| 180 |
that both the value and the containing row will be passed as |
| 181 |
arguments to the conversion function (so, i.e., the conversion function |
| 182 |
should accept two arguments). |
| 183 |
|
| 184 |
When multiple fields are converted in a single call, the conversions |
| 185 |
are independent of each other. Each conversion sees the original row:: |
| 186 |
|
| 187 |
>>> # multiple conversions do not affect each other |
| 188 |
... table13 = etl.convert(table1, { |
| 189 |
... "foo": lambda foo, row: row.bar, |
| 190 |
... "bar": lambda bar, row: row.foo, |
| 191 |
... }, pass_row=True) |
| 192 |
>>> table13 |
| 193 |
+-------+-----+-----+ |
| 194 |
| foo | bar | baz | |
| 195 |
+=======+=====+=====+ |
| 196 |
| '2.4' | 'A' | 12 | |
| 197 |
+-------+-----+-----+ |
| 198 |
| '5.7' | 'B' | 34 | |
| 199 |
+-------+-----+-----+ |
| 200 |
| '1.2' | 'C' | 56 | |
| 201 |
+-------+-----+-----+ |
| 202 |
|
| 203 |
Also accepts `failonerror` and `errorvalue` keyword arguments, |
| 204 |
documented under :func:`petl.config.failonerror` |
| 205 |
|
| 206 |
The ``trusted`` keyword argument can be used to specify whether the |
| 207 |
expression is trusted. See `:func:`petl.util.base.expr` for details. |
| 208 |
|
| 209 |
""" |
| 210 |
|
| 211 |
converters = None |
| 212 |
if len(args) == 0: |
| 213 |
# no conversion specified, can be set afterwards via suffix notation |
| 214 |
pass |
| 215 |
elif len(args) == 1: |
| 216 |
converters = args[0] |
| 217 |
elif len(args) > 1: |
| 218 |
converters = dict() |
| 219 |
# assume first arg is field name or spec |
| 220 |
field = args[0] |
| 221 |
if len(args) == 2: |
| 222 |
conv = args[1] |
| 223 |
else: |
| 224 |
conv = args[1:] |
| 225 |
if isinstance(field, (list, tuple)): # allow for multiple fields |
| 226 |
for f in field: |
| 227 |
converters[f] = conv |
| 228 |
else: |
| 229 |
converters[field] = conv |
| 230 |
return FieldConvertView(table, converters, **kwargs) |
| 231 |
|
| 232 |
|
| 233 |
Table.convert = convert |
| 234 |
|
| 235 |
|
| 236 |
def convertall(table, *args, **kwargs): |
| 237 |
""" |
| 238 |
Convenience function to convert all fields in the table using a common |
| 239 |
function or mapping. See also :func:`convert`. |
| 240 |
|
| 241 |
The ``where`` keyword argument can be given with a callable or expression |
| 242 |
which is evaluated on each row and which should return True if the |
| 243 |
conversion should be applied on that row, else False. |
| 244 |
|
| 245 |
""" |
| 246 |
|
| 247 |
# TODO don't read the data twice! |
| 248 |
return convert(table, fieldnames(table), *args, **kwargs) |
| 249 |
|
| 250 |
|
| 251 |
Table.convertall = convertall |
| 252 |
|
| 253 |
|
| 254 |
def replace(table, field, a, b, **kwargs): |
| 255 |
""" |
| 256 |
Convenience function to replace all occurrences of `a` with `b` under the |
| 257 |
given field. See also :func:`convert`. |
| 258 |
|
| 259 |
The ``where`` keyword argument can be given with a callable or expression |
| 260 |
which is evaluated on each row and which should return True if the |
| 261 |
conversion should be applied on that row, else False. |
| 262 |
|
| 263 |
""" |
| 264 |
|
| 265 |
return convert(table, field, {a: b}, **kwargs) |
| 266 |
|
| 267 |
|
| 268 |
Table.replace = replace |
| 269 |
|
| 270 |
|
| 271 |
def replaceall(table, a, b, **kwargs): |
| 272 |
""" |
| 273 |
Convenience function to replace all instances of `a` with `b` under all |
| 274 |
fields. See also :func:`convertall`. |
| 275 |
|
| 276 |
The ``where`` keyword argument can be given with a callable or expression |
| 277 |
which is evaluated on each row and which should return True if the |
| 278 |
conversion should be applied on that row, else False. |
| 279 |
|
| 280 |
""" |
| 281 |
|
| 282 |
return convertall(table, {a: b}, **kwargs) |
| 283 |
|
| 284 |
|
| 285 |
Table.replaceall = replaceall |
| 286 |
|
| 287 |
|
| 288 |
def update(table, field, value, **kwargs): |
| 289 |
""" |
| 290 |
Convenience function to convert a field to a fixed value. Accepts the |
| 291 |
``where`` keyword argument. See also :func:`convert`. |
| 292 |
|
| 293 |
""" |
| 294 |
|
| 295 |
return convert(table, field, lambda v: value, **kwargs) |
| 296 |
|
| 297 |
|
| 298 |
Table.update = update |
| 299 |
|
| 300 |
|
| 301 |
def convertnumbers(table, strict=False, **kwargs): |
| 302 |
""" |
| 303 |
Convenience function to convert all field values to numbers where |
| 304 |
possible. E.g.:: |
| 305 |
|
| 306 |
>>> import petl as etl |
| 307 |
>>> table1 = [['foo', 'bar', 'baz', 'quux'], |
| 308 |
... ['1', '3.0', '9+3j', 'aaa'], |
| 309 |
... ['2', '1.3', '7+2j', None]] |
| 310 |
>>> table2 = etl.convertnumbers(table1) |
| 311 |
>>> table2 |
| 312 |
+-----+-----+--------+-------+ |
| 313 |
| foo | bar | baz | quux | |
| 314 |
+=====+=====+========+=======+ |
| 315 |
| 1 | 3.0 | (9+3j) | 'aaa' | |
| 316 |
+-----+-----+--------+-------+ |
| 317 |
| 2 | 1.3 | (7+2j) | None | |
| 318 |
+-----+-----+--------+-------+ |
| 319 |
|
| 320 |
""" |
| 321 |
|
| 322 |
return convertall(table, numparser(strict), **kwargs) |
| 323 |
|
| 324 |
|
| 325 |
Table.convertnumbers = convertnumbers |
| 326 |
|
| 327 |
|
| 328 |
class FieldConvertView(Table): |
| 329 |
|
| 330 |
def __init__(self, source, converters=None, failonerror=None, |
| 331 |
errorvalue=None, where=None, pass_row=False, trusted=True): |
| 332 |
self.source = source |
| 333 |
if converters is None: |
| 334 |
self.converters = dict() |
| 335 |
elif isinstance(converters, dict): |
| 336 |
self.converters = converters |
| 337 |
elif isinstance(converters, (tuple, list)): |
| 338 |
self.converters = dict([(i, v) for i, v in enumerate(converters)]) |
| 339 |
else: |
| 340 |
raise ArgumentError('unexpected converters: %r' % converters) |
| 341 |
self.failonerror = (config.failonerror if failonerror is None |
| 342 |
else failonerror) |
| 343 |
self.errorvalue = errorvalue |
| 344 |
self.where = where |
| 345 |
self.pass_row = pass_row |
| 346 |
self.trusted = trusted |
| 347 |
|
| 348 |
def __iter__(self): |
| 349 |
return iterfieldconvert(self.source, self.converters, self.failonerror, |
| 350 |
self.errorvalue, self.where, self.pass_row, self.trusted) |
| 351 |
|
| 352 |
def __setitem__(self, key, value): |
| 353 |
self.converters[key] = value |
| 354 |
|
| 355 |
|
| 356 |
def iterfieldconvert(source, converters, failonerror, errorvalue, where, |
| 357 |
pass_row, trusted): |
| 358 |
|
| 359 |
# grab the fields in the source table |
| 360 |
it = iter(source) |
| 361 |
try: |
| 362 |
hdr = next(it) |
| 363 |
flds = list(map(text_type, hdr)) |
| 364 |
yield tuple(hdr) # these are not modified |
| 365 |
except StopIteration: |
| 366 |
hdr = flds = [] # converters will fail selecting a field |
| 367 |
|
| 368 |
# build converter functions |
| 369 |
converter_functions = dict() |
| 370 |
for k, c in converters.items(): |
| 371 |
|
| 372 |
# turn field names into row indices |
| 373 |
if not isinstance(k, integer_types): |
| 374 |
try: |
| 375 |
k = flds.index(k) |
| 376 |
except ValueError: # not in list |
| 377 |
raise FieldSelectionError(k) |
| 378 |
assert isinstance(k, int), 'expected integer, found %r' % k |
| 379 |
|
| 380 |
# is converter a function? |
| 381 |
if callable(c): |
| 382 |
converter_functions[k] = c |
| 383 |
|
| 384 |
# is converter a method name? |
| 385 |
elif isinstance(c, string_types): |
| 386 |
converter_functions[k] = methodcaller(c) |
| 387 |
|
| 388 |
# is converter a method name with arguments? |
| 389 |
elif isinstance(c, (tuple, list)) and isinstance(c[0], string_types): |
| 390 |
methnm = c[0] |
| 391 |
methargs = c[1:] |
| 392 |
converter_functions[k] = methodcaller(methnm, *methargs) |
| 393 |
|
| 394 |
# is converter a dictionary? |
| 395 |
elif isinstance(c, dict): |
| 396 |
converter_functions[k] = dictconverter(c) |
| 397 |
|
| 398 |
# is it something else? |
| 399 |
elif c is None: |
| 400 |
pass # ignore |
| 401 |
else: |
| 402 |
raise ArgumentError( |
| 403 |
'unexpected converter specification on field %r: %r' % (k, c) |
| 404 |
) |
| 405 |
|
| 406 |
# define a function to transform a value |
| 407 |
def transform_value(i, v, *args): |
| 408 |
if i not in converter_functions: |
| 409 |
# no converter defined on this field, return value as-is |
| 410 |
return v |
| 411 |
else: |
| 412 |
try: |
| 413 |
return converter_functions[i](v, *args) |
| 414 |
except Exception as e: |
| 415 |
if failonerror == 'inline': |
| 416 |
return e |
| 417 |
elif failonerror: |
| 418 |
raise e |
| 419 |
else: |
| 420 |
return errorvalue |
| 421 |
|
| 422 |
# define a function to transform a row |
| 423 |
if pass_row: |
| 424 |
def transform_row(_row): |
| 425 |
return tuple(transform_value(i, v, _row) |
| 426 |
for i, v in enumerate(_row)) |
| 427 |
else: |
| 428 |
def transform_row(_row): |
| 429 |
return tuple(transform_value(i, v) |
| 430 |
for i, v in enumerate(_row)) |
| 431 |
|
| 432 |
# prepare where function |
| 433 |
if isinstance(where, string_types): |
| 434 |
where = expr(where, trusted=trusted) |
| 435 |
elif where is not None: |
| 436 |
assert callable(where), 'expected callable for "where" argument, ' \ |
| 437 |
'found %r' % where |
| 438 |
|
| 439 |
# prepare iterator |
| 440 |
if pass_row or where: |
| 441 |
# wrap rows as records |
| 442 |
it = (Record(row, flds) for row in it) |
| 443 |
|
| 444 |
# construct the data rows |
| 445 |
if where is None: |
| 446 |
# simple case, transform all rows |
| 447 |
for row in it: |
| 448 |
yield transform_row(row) |
| 449 |
else: |
| 450 |
# conditionally transform rows |
| 451 |
for row in it: |
| 452 |
if where(row): |
| 453 |
yield transform_row(row) |
| 454 |
else: |
| 455 |
yield row |
| 456 |
|
| 457 |
|
| 458 |
def methodcaller(nm, *args): |
| 459 |
return lambda v: getattr(v, nm)(*args) |
| 460 |
|
| 461 |
|
| 462 |
def dictconverter(d): |
| 463 |
def conv(v): |
| 464 |
try: |
| 465 |
if v in d: |
| 466 |
return d[v] |
| 467 |
else: |
| 468 |
return v |
| 469 |
except TypeError: |
| 470 |
# value is not hashable |
| 471 |
return v |
| 472 |
return conv |
| 473 |
|
| 474 |
|
| 475 |
def format(table, field, fmt, **kwargs): |
| 476 |
""" |
| 477 |
Convenience function to format all values in the given `field` using the |
| 478 |
`fmt` format string. |
| 479 |
|
| 480 |
The ``where`` keyword argument can be given with a callable or expression |
| 481 |
which is evaluated on each row and which should return True if the |
| 482 |
conversion should be applied on that row, else False. |
| 483 |
|
| 484 |
""" |
| 485 |
|
| 486 |
conv = lambda v: fmt.format(v) |
| 487 |
return convert(table, field, conv, **kwargs) |
| 488 |
|
| 489 |
|
| 490 |
Table.format = format |
| 491 |
|
| 492 |
|
| 493 |
def formatall(table, fmt, **kwargs): |
| 494 |
""" |
| 495 |
Convenience function to format all values in all fields using the |
| 496 |
`fmt` format string. |
| 497 |
|
| 498 |
The ``where`` keyword argument can be given with a callable or expression |
| 499 |
which is evaluated on each row and which should return True if the |
| 500 |
conversion should be applied on that row, else False. |
| 501 |
|
| 502 |
""" |
| 503 |
|
| 504 |
conv = lambda v: fmt.format(v) |
| 505 |
return convertall(table, conv, **kwargs) |
| 506 |
|
| 507 |
|
| 508 |
Table.formatall = formatall |
| 509 |
|
| 510 |
|
| 511 |
def interpolate(table, field, fmt, **kwargs): |
| 512 |
""" |
| 513 |
Convenience function to interpolate all values in the given `field` using |
| 514 |
the `fmt` string. |
| 515 |
|
| 516 |
The ``where`` keyword argument can be given with a callable or expression |
| 517 |
which is evaluated on each row and which should return True if the |
| 518 |
conversion should be applied on that row, else False. |
| 519 |
|
| 520 |
""" |
| 521 |
|
| 522 |
conv = lambda v: fmt % v |
| 523 |
return convert(table, field, conv, **kwargs) |
| 524 |
|
| 525 |
|
| 526 |
Table.interpolate = interpolate |
| 527 |
|
| 528 |
|
| 529 |
def interpolateall(table, fmt, **kwargs): |
| 530 |
""" |
| 531 |
Convenience function to interpolate all values in all fields using |
| 532 |
the `fmt` string. |
| 533 |
|
| 534 |
The ``where`` keyword argument can be given with a callable or expression |
| 535 |
which is evaluated on each row and which should return True if the |
| 536 |
conversion should be applied on that row, else False. |
| 537 |
|
| 538 |
""" |
| 539 |
|
| 540 |
conv = lambda v: fmt % v |
| 541 |
return convertall(table, conv, **kwargs) |
| 542 |
|
| 543 |
|
| 544 |
Table.interpolateall = interpolateall |