| 1 |
from __future__ import absolute_import, print_function, division |
| 2 |
|
| 3 |
|
| 4 |
import itertools |
| 5 |
import collections |
| 6 |
import operator |
| 7 |
from petl.compat import next, text_type |
| 8 |
|
| 9 |
|
| 10 |
from petl.comparison import comparable_itemgetter |
| 11 |
from petl.util.base import Table, rowgetter, values, itervalues, \ |
| 12 |
header, data, asindices |
| 13 |
from petl.transform.sorts import sort |
| 14 |
|
| 15 |
|
| 16 |
def melt(table, key=None, variables=None, variablefield='variable', |
| 17 |
valuefield='value'): |
| 18 |
""" |
| 19 |
Reshape a table, melting fields into data. E.g.:: |
| 20 |
|
| 21 |
>>> import petl as etl |
| 22 |
>>> table1 = [['id', 'gender', 'age'], |
| 23 |
... [1, 'F', 12], |
| 24 |
... [2, 'M', 17], |
| 25 |
... [3, 'M', 16]] |
| 26 |
>>> table2 = etl.melt(table1, 'id') |
| 27 |
>>> table2.lookall() |
| 28 |
+----+----------+-------+ |
| 29 |
| id | variable | value | |
| 30 |
+====+==========+=======+ |
| 31 |
| 1 | 'gender' | 'F' | |
| 32 |
+----+----------+-------+ |
| 33 |
| 1 | 'age' | 12 | |
| 34 |
+----+----------+-------+ |
| 35 |
| 2 | 'gender' | 'M' | |
| 36 |
+----+----------+-------+ |
| 37 |
| 2 | 'age' | 17 | |
| 38 |
+----+----------+-------+ |
| 39 |
| 3 | 'gender' | 'M' | |
| 40 |
+----+----------+-------+ |
| 41 |
| 3 | 'age' | 16 | |
| 42 |
+----+----------+-------+ |
| 43 |
|
| 44 |
>>> # compound keys are supported |
| 45 |
... table3 = [['id', 'time', 'height', 'weight'], |
| 46 |
... [1, 11, 66.4, 12.2], |
| 47 |
... [2, 16, 53.2, 17.3], |
| 48 |
... [3, 12, 34.5, 9.4]] |
| 49 |
>>> table4 = etl.melt(table3, key=['id', 'time']) |
| 50 |
>>> table4.lookall() |
| 51 |
+----+------+----------+-------+ |
| 52 |
| id | time | variable | value | |
| 53 |
+====+======+==========+=======+ |
| 54 |
| 1 | 11 | 'height' | 66.4 | |
| 55 |
+----+------+----------+-------+ |
| 56 |
| 1 | 11 | 'weight' | 12.2 | |
| 57 |
+----+------+----------+-------+ |
| 58 |
| 2 | 16 | 'height' | 53.2 | |
| 59 |
+----+------+----------+-------+ |
| 60 |
| 2 | 16 | 'weight' | 17.3 | |
| 61 |
+----+------+----------+-------+ |
| 62 |
| 3 | 12 | 'height' | 34.5 | |
| 63 |
+----+------+----------+-------+ |
| 64 |
| 3 | 12 | 'weight' | 9.4 | |
| 65 |
+----+------+----------+-------+ |
| 66 |
|
| 67 |
>>> # a subset of variable fields can be selected |
| 68 |
... table5 = etl.melt(table3, key=['id', 'time'], |
| 69 |
... variables=['height']) |
| 70 |
>>> table5.lookall() |
| 71 |
+----+------+----------+-------+ |
| 72 |
| id | time | variable | value | |
| 73 |
+====+======+==========+=======+ |
| 74 |
| 1 | 11 | 'height' | 66.4 | |
| 75 |
+----+------+----------+-------+ |
| 76 |
| 2 | 16 | 'height' | 53.2 | |
| 77 |
+----+------+----------+-------+ |
| 78 |
| 3 | 12 | 'height' | 34.5 | |
| 79 |
+----+------+----------+-------+ |
| 80 |
|
| 81 |
See also :func:`petl.transform.reshape.recast`. |
| 82 |
|
| 83 |
""" |
| 84 |
|
| 85 |
return MeltView(table, key=key, variables=variables, |
| 86 |
variablefield=variablefield, |
| 87 |
valuefield=valuefield) |
| 88 |
|
| 89 |
|
| 90 |
Table.melt = melt |
| 91 |
|
| 92 |
|
| 93 |
class MeltView(Table): |
| 94 |
|
| 95 |
def __init__(self, source, key=None, variables=None, |
| 96 |
variablefield='variable', valuefield='value'): |
| 97 |
self.source = source |
| 98 |
self.key = key |
| 99 |
self.variables = variables |
| 100 |
self.variablefield = variablefield |
| 101 |
self.valuefield = valuefield |
| 102 |
|
| 103 |
def __iter__(self): |
| 104 |
return itermelt(self.source, self.key, self.variables, |
| 105 |
self.variablefield, self.valuefield) |
| 106 |
|
| 107 |
|
| 108 |
def itermelt(source, key, variables, variablefield, valuefield): |
| 109 |
if key is None and variables is None: |
| 110 |
raise ValueError('either key or variables must be specified') |
| 111 |
|
| 112 |
it = iter(source) |
| 113 |
try: |
| 114 |
hdr = next(it) |
| 115 |
except StopIteration: |
| 116 |
return |
| 117 |
|
| 118 |
# determine key and variable field indices |
| 119 |
key_indices = variables_indices = None |
| 120 |
if key is not None: |
| 121 |
key_indices = asindices(hdr, key) |
| 122 |
if variables is not None: |
| 123 |
if not isinstance(variables, (list, tuple)): |
| 124 |
variables = (variables,) |
| 125 |
variables_indices = asindices(hdr, variables) |
| 126 |
|
| 127 |
if key is None: |
| 128 |
# assume key is fields not in variables |
| 129 |
key_indices = [i for i in range(len(hdr)) |
| 130 |
if i not in variables_indices] |
| 131 |
if variables is None: |
| 132 |
# assume variables are fields not in key |
| 133 |
variables_indices = [i for i in range(len(hdr)) |
| 134 |
if i not in key_indices] |
| 135 |
variables = [hdr[i] for i in variables_indices] |
| 136 |
|
| 137 |
getkey = rowgetter(*key_indices) |
| 138 |
|
| 139 |
# determine the output fields |
| 140 |
outhdr = [hdr[i] for i in key_indices] |
| 141 |
outhdr.append(variablefield) |
| 142 |
outhdr.append(valuefield) |
| 143 |
yield tuple(outhdr) |
| 144 |
|
| 145 |
# construct the output data |
| 146 |
for row in it: |
| 147 |
k = getkey(row) |
| 148 |
for v, i in zip(variables, variables_indices): |
| 149 |
try: |
| 150 |
o = list(k) # populate with key values initially |
| 151 |
o.append(v) # add variable |
| 152 |
o.append(row[i]) # add value |
| 153 |
yield tuple(o) |
| 154 |
except IndexError: |
| 155 |
# row is missing this value, and melt() should yield no row |
| 156 |
pass |
| 157 |
|
| 158 |
|
| 159 |
def recast(table, key=None, variablefield='variable', valuefield='value', |
| 160 |
samplesize=1000, reducers=None, missing=None): |
| 161 |
""" |
| 162 |
Recast molten data. E.g.:: |
| 163 |
|
| 164 |
>>> import petl as etl |
| 165 |
>>> table1 = [['id', 'variable', 'value'], |
| 166 |
... [3, 'age', 16], |
| 167 |
... [1, 'gender', 'F'], |
| 168 |
... [2, 'gender', 'M'], |
| 169 |
... [2, 'age', 17], |
| 170 |
... [1, 'age', 12], |
| 171 |
... [3, 'gender', 'M']] |
| 172 |
>>> table2 = etl.recast(table1) |
| 173 |
>>> table2 |
| 174 |
+----+-----+--------+ |
| 175 |
| id | age | gender | |
| 176 |
+====+=====+========+ |
| 177 |
| 1 | 12 | 'F' | |
| 178 |
+----+-----+--------+ |
| 179 |
| 2 | 17 | 'M' | |
| 180 |
+----+-----+--------+ |
| 181 |
| 3 | 16 | 'M' | |
| 182 |
+----+-----+--------+ |
| 183 |
|
| 184 |
>>> # specifying variable and value fields |
| 185 |
... table3 = [['id', 'vars', 'vals'], |
| 186 |
... [3, 'age', 16], |
| 187 |
... [1, 'gender', 'F'], |
| 188 |
... [2, 'gender', 'M'], |
| 189 |
... [2, 'age', 17], |
| 190 |
... [1, 'age', 12], |
| 191 |
... [3, 'gender', 'M']] |
| 192 |
>>> table4 = etl.recast(table3, variablefield='vars', valuefield='vals') |
| 193 |
>>> table4 |
| 194 |
+----+-----+--------+ |
| 195 |
| id | age | gender | |
| 196 |
+====+=====+========+ |
| 197 |
| 1 | 12 | 'F' | |
| 198 |
+----+-----+--------+ |
| 199 |
| 2 | 17 | 'M' | |
| 200 |
+----+-----+--------+ |
| 201 |
| 3 | 16 | 'M' | |
| 202 |
+----+-----+--------+ |
| 203 |
|
| 204 |
>>> # if there are multiple values for each key/variable pair, and no |
| 205 |
... # reducers function is provided, then all values will be listed |
| 206 |
... table6 = [['id', 'time', 'variable', 'value'], |
| 207 |
... [1, 11, 'weight', 66.4], |
| 208 |
... [1, 14, 'weight', 55.2], |
| 209 |
... [2, 12, 'weight', 53.2], |
| 210 |
... [2, 16, 'weight', 43.3], |
| 211 |
... [3, 12, 'weight', 34.5], |
| 212 |
... [3, 17, 'weight', 49.4]] |
| 213 |
>>> table7 = etl.recast(table6, key='id') |
| 214 |
>>> table7 |
| 215 |
+----+--------------+ |
| 216 |
| id | weight | |
| 217 |
+====+==============+ |
| 218 |
| 1 | [66.4, 55.2] | |
| 219 |
+----+--------------+ |
| 220 |
| 2 | [53.2, 43.3] | |
| 221 |
+----+--------------+ |
| 222 |
| 3 | [34.5, 49.4] | |
| 223 |
+----+--------------+ |
| 224 |
|
| 225 |
>>> # multiple values can be reduced via an aggregation function |
| 226 |
... def mean(values): |
| 227 |
... return float(sum(values)) / len(values) |
| 228 |
... |
| 229 |
>>> table8 = etl.recast(table6, key='id', reducers={'weight': mean}) |
| 230 |
>>> table8 |
| 231 |
+----+--------------------+ |
| 232 |
| id | weight | |
| 233 |
+====+====================+ |
| 234 |
| 1 | 60.800000000000004 | |
| 235 |
+----+--------------------+ |
| 236 |
| 2 | 48.25 | |
| 237 |
+----+--------------------+ |
| 238 |
| 3 | 41.95 | |
| 239 |
+----+--------------------+ |
| 240 |
|
| 241 |
>>> # missing values are padded with whatever is provided via the |
| 242 |
... # missing keyword argument (None by default) |
| 243 |
... table9 = [['id', 'variable', 'value'], |
| 244 |
... [1, 'gender', 'F'], |
| 245 |
... [2, 'age', 17], |
| 246 |
... [1, 'age', 12], |
| 247 |
... [3, 'gender', 'M']] |
| 248 |
>>> table10 = etl.recast(table9, key='id') |
| 249 |
>>> table10 |
| 250 |
+----+------+--------+ |
| 251 |
| id | age | gender | |
| 252 |
+====+======+========+ |
| 253 |
| 1 | 12 | 'F' | |
| 254 |
+----+------+--------+ |
| 255 |
| 2 | 17 | None | |
| 256 |
+----+------+--------+ |
| 257 |
| 3 | None | 'M' | |
| 258 |
+----+------+--------+ |
| 259 |
|
| 260 |
Note that the table is scanned once to discover variables, then a second |
| 261 |
time to reshape the data and recast variables as fields. How many rows are |
| 262 |
scanned in the first pass is determined by the `samplesize` argument. |
| 263 |
|
| 264 |
See also :func:`petl.transform.reshape.melt`. |
| 265 |
|
| 266 |
""" |
| 267 |
|
| 268 |
return RecastView(table, key=key, variablefield=variablefield, |
| 269 |
valuefield=valuefield, samplesize=samplesize, |
| 270 |
reducers=reducers, missing=missing) |
| 271 |
|
| 272 |
|
| 273 |
Table.recast = recast |
| 274 |
|
| 275 |
|
| 276 |
class RecastView(Table): |
| 277 |
|
| 278 |
def __init__(self, source, key=None, variablefield='variable', |
| 279 |
valuefield='value', samplesize=1000, reducers=None, |
| 280 |
missing=None): |
| 281 |
self.source = source |
| 282 |
self.key = key |
| 283 |
self.variablefield = variablefield |
| 284 |
self.valuefield = valuefield |
| 285 |
self.samplesize = samplesize |
| 286 |
if reducers is None: |
| 287 |
self.reducers = dict() |
| 288 |
else: |
| 289 |
self.reducers = reducers |
| 290 |
self.missing = missing |
| 291 |
|
| 292 |
def __iter__(self): |
| 293 |
return iterrecast(self.source, self.key, self.variablefield, |
| 294 |
self.valuefield, self.samplesize, self.reducers, |
| 295 |
self.missing) |
| 296 |
|
| 297 |
|
| 298 |
def iterrecast(source, key, variablefield, valuefield, |
| 299 |
samplesize, reducers, missing): |
| 300 |
|
| 301 |
# TODO only make one pass through the data |
| 302 |
|
| 303 |
it = iter(source) |
| 304 |
try: |
| 305 |
hdr = next(it) |
| 306 |
except StopIteration: |
| 307 |
return |
| 308 |
flds = list(map(text_type, hdr)) |
| 309 |
|
| 310 |
# normalise some stuff |
| 311 |
keyfields = key |
| 312 |
variablefields = variablefield # N.B., could be more than one |
| 313 |
|
| 314 |
# normalise key fields |
| 315 |
if keyfields and not isinstance(keyfields, (list, tuple)): |
| 316 |
keyfields = (keyfields,) |
| 317 |
|
| 318 |
# normalise variable fields |
| 319 |
if variablefields: |
| 320 |
if isinstance(variablefields, dict): |
| 321 |
pass # handle this later |
| 322 |
elif not isinstance(variablefields, (list, tuple)): |
| 323 |
variablefields = (variablefields,) |
| 324 |
|
| 325 |
# infer key fields |
| 326 |
if not keyfields: |
| 327 |
# assume keyfields is fields not in variables |
| 328 |
keyfields = [f for f in flds |
| 329 |
if f not in variablefields and f != valuefield] |
| 330 |
|
| 331 |
# infer key fields |
| 332 |
if not variablefields: |
| 333 |
# assume variables are fields not in keyfields |
| 334 |
variablefields = [f for f in flds |
| 335 |
if f not in keyfields and f != valuefield] |
| 336 |
|
| 337 |
# sanity checks |
| 338 |
assert valuefield in flds, 'invalid value field: %s' % valuefield |
| 339 |
assert valuefield not in keyfields, 'value field cannot be keyfields' |
| 340 |
assert valuefield not in variablefields, \ |
| 341 |
'value field cannot be variable field' |
| 342 |
for f in keyfields: |
| 343 |
assert f in flds, 'invalid keyfields field: %s' % f |
| 344 |
for f in variablefields: |
| 345 |
assert f in flds, 'invalid variable field: %s' % f |
| 346 |
|
| 347 |
# we'll need these later |
| 348 |
valueindex = flds.index(valuefield) |
| 349 |
keyindices = [flds.index(f) for f in keyfields] |
| 350 |
variableindices = [flds.index(f) for f in variablefields] |
| 351 |
|
| 352 |
# determine the actual variable names to be cast as fields |
| 353 |
if isinstance(variablefields, dict): |
| 354 |
# user supplied dictionary |
| 355 |
variables = variablefields |
| 356 |
else: |
| 357 |
variables = collections.defaultdict(set) |
| 358 |
# sample the data to discover variables to be cast as fields |
| 359 |
for row in itertools.islice(it, 0, samplesize): |
| 360 |
for i, f in zip(variableindices, variablefields): |
| 361 |
variables[f].add(row[i]) |
| 362 |
for f in variables: |
| 363 |
# turn from sets to sorted lists |
| 364 |
variables[f] = sorted(variables[f]) |
| 365 |
|
| 366 |
# finished the first pass |
| 367 |
|
| 368 |
# determine the output fields |
| 369 |
outhdr = list(keyfields) |
| 370 |
for f in variablefields: |
| 371 |
outhdr.extend(variables[f]) |
| 372 |
yield tuple(outhdr) |
| 373 |
|
| 374 |
# output data |
| 375 |
|
| 376 |
source = sort(source, key=keyfields) |
| 377 |
it = itertools.islice(source, 1, None) # skip header row |
| 378 |
getsortablekey = comparable_itemgetter(*keyindices) |
| 379 |
getactualkey = operator.itemgetter(*keyindices) |
| 380 |
|
| 381 |
# process sorted data in newfields |
| 382 |
groups = itertools.groupby(it, key=getsortablekey) |
| 383 |
for _, group in groups: |
| 384 |
# may need to iterate over the group more than once |
| 385 |
group = list(group) |
| 386 |
# N.B., key returned by groupby may be wrapped as SortableItem, we want |
| 387 |
# to output the actual key value, get it from the first row in the group |
| 388 |
key_value = getactualkey(group[0]) |
| 389 |
if len(keyfields) > 1: |
| 390 |
out_row = list(key_value) |
| 391 |
else: |
| 392 |
out_row = [key_value] |
| 393 |
for f, i in zip(variablefields, variableindices): |
| 394 |
for variable in variables[f]: |
| 395 |
# collect all values for the current variable |
| 396 |
vals = [r[valueindex] for r in group if r[i] == variable] |
| 397 |
if len(vals) == 0: |
| 398 |
val = missing |
| 399 |
elif len(vals) == 1: |
| 400 |
val = vals[0] |
| 401 |
else: |
| 402 |
if variable in reducers: |
| 403 |
redu = reducers[variable] |
| 404 |
else: |
| 405 |
redu = list # list all values |
| 406 |
val = redu(vals) |
| 407 |
out_row.append(val) |
| 408 |
yield tuple(out_row) |
| 409 |
|
| 410 |
|
| 411 |
def transpose(table): |
| 412 |
""" |
| 413 |
Transpose rows into columns. E.g.:: |
| 414 |
|
| 415 |
>>> import petl as etl |
| 416 |
>>> table1 = [['id', 'colour'], |
| 417 |
... [1, 'blue'], |
| 418 |
... [2, 'red'], |
| 419 |
... [3, 'purple'], |
| 420 |
... [5, 'yellow'], |
| 421 |
... [7, 'orange']] |
| 422 |
>>> table2 = etl.transpose(table1) |
| 423 |
>>> table2 |
| 424 |
+----------+--------+-------+----------+----------+----------+ |
| 425 |
| id | 1 | 2 | 3 | 5 | 7 | |
| 426 |
+==========+========+=======+==========+==========+==========+ |
| 427 |
| 'colour' | 'blue' | 'red' | 'purple' | 'yellow' | 'orange' | |
| 428 |
+----------+--------+-------+----------+----------+----------+ |
| 429 |
|
| 430 |
See also :func:`petl.transform.reshape.recast`. |
| 431 |
|
| 432 |
""" |
| 433 |
|
| 434 |
return TransposeView(table) |
| 435 |
|
| 436 |
|
| 437 |
Table.transpose = transpose |
| 438 |
|
| 439 |
|
| 440 |
class TransposeView(Table): |
| 441 |
|
| 442 |
def __init__(self, source): |
| 443 |
self.source = source |
| 444 |
|
| 445 |
def __iter__(self): |
| 446 |
return itertranspose(self.source) |
| 447 |
|
| 448 |
|
| 449 |
def itertranspose(source): |
| 450 |
hdr = header(source) |
| 451 |
its = [iter(source) for _ in hdr] |
| 452 |
for i in range(len(hdr)): |
| 453 |
yield tuple(row[i] for row in its[i]) |
| 454 |
|
| 455 |
|
| 456 |
def pivot(table, f1, f2, f3, aggfun, missing=None, |
| 457 |
presorted=False, buffersize=None, tempdir=None, cache=True): |
| 458 |
""" |
| 459 |
Construct a pivot table. E.g.:: |
| 460 |
|
| 461 |
>>> import petl as etl |
| 462 |
>>> table1 = [['region', 'gender', 'style', 'units'], |
| 463 |
... ['east', 'boy', 'tee', 12], |
| 464 |
... ['east', 'boy', 'golf', 14], |
| 465 |
... ['east', 'boy', 'fancy', 7], |
| 466 |
... ['east', 'girl', 'tee', 3], |
| 467 |
... ['east', 'girl', 'golf', 8], |
| 468 |
... ['east', 'girl', 'fancy', 18], |
| 469 |
... ['west', 'boy', 'tee', 12], |
| 470 |
... ['west', 'boy', 'golf', 15], |
| 471 |
... ['west', 'boy', 'fancy', 8], |
| 472 |
... ['west', 'girl', 'tee', 6], |
| 473 |
... ['west', 'girl', 'golf', 16], |
| 474 |
... ['west', 'girl', 'fancy', 1]] |
| 475 |
>>> table2 = etl.pivot(table1, 'region', 'gender', 'units', sum) |
| 476 |
>>> table2 |
| 477 |
+--------+-----+------+ |
| 478 |
| region | boy | girl | |
| 479 |
+========+=====+======+ |
| 480 |
| 'east' | 33 | 29 | |
| 481 |
+--------+-----+------+ |
| 482 |
| 'west' | 35 | 23 | |
| 483 |
+--------+-----+------+ |
| 484 |
|
| 485 |
>>> table3 = etl.pivot(table1, 'region', 'style', 'units', sum) |
| 486 |
>>> table3 |
| 487 |
+--------+-------+------+-----+ |
| 488 |
| region | fancy | golf | tee | |
| 489 |
+========+=======+======+=====+ |
| 490 |
| 'east' | 25 | 22 | 15 | |
| 491 |
+--------+-------+------+-----+ |
| 492 |
| 'west' | 9 | 31 | 18 | |
| 493 |
+--------+-------+------+-----+ |
| 494 |
|
| 495 |
>>> table4 = etl.pivot(table1, 'gender', 'style', 'units', sum) |
| 496 |
>>> table4 |
| 497 |
+--------+-------+------+-----+ |
| 498 |
| gender | fancy | golf | tee | |
| 499 |
+========+=======+======+=====+ |
| 500 |
| 'boy' | 15 | 29 | 24 | |
| 501 |
+--------+-------+------+-----+ |
| 502 |
| 'girl' | 19 | 24 | 9 | |
| 503 |
+--------+-------+------+-----+ |
| 504 |
|
| 505 |
See also :func:`petl.transform.reshape.recast`. |
| 506 |
|
| 507 |
""" |
| 508 |
|
| 509 |
return PivotView(table, f1, f2, f3, aggfun, missing=missing, |
| 510 |
presorted=presorted, buffersize=buffersize, |
| 511 |
tempdir=tempdir, cache=cache) |
| 512 |
|
| 513 |
|
| 514 |
Table.pivot = pivot |
| 515 |
|
| 516 |
|
| 517 |
class PivotView(Table): |
| 518 |
|
| 519 |
def __init__(self, source, f1, f2, f3, aggfun, missing=None, |
| 520 |
presorted=False, buffersize=None, tempdir=None, cache=True): |
| 521 |
if presorted: |
| 522 |
self.source = source |
| 523 |
else: |
| 524 |
self.source = sort(source, key=(f1, f2), buffersize=buffersize, |
| 525 |
tempdir=tempdir, cache=cache) |
| 526 |
self.f1, self.f2, self.f3 = f1, f2, f3 |
| 527 |
self.aggfun = aggfun |
| 528 |
self.missing = missing |
| 529 |
|
| 530 |
def __iter__(self): |
| 531 |
return iterpivot(self.source, self.f1, self.f2, self.f3, self.aggfun, |
| 532 |
self.missing) |
| 533 |
|
| 534 |
|
| 535 |
def iterpivot(source, f1, f2, f3, aggfun, missing): |
| 536 |
|
| 537 |
# first pass - collect fields |
| 538 |
f2vals = set(itervalues(source, f2)) # TODO only make one pass |
| 539 |
f2vals = list(f2vals) |
| 540 |
f2vals.sort() |
| 541 |
outhdr = [f1] |
| 542 |
outhdr.extend(f2vals) |
| 543 |
yield tuple(outhdr) |
| 544 |
|
| 545 |
# second pass - generate output |
| 546 |
it = iter(source) |
| 547 |
try: |
| 548 |
hdr = next(it) |
| 549 |
except StopIteration: |
| 550 |
hdr = [] |
| 551 |
flds = list(map(text_type, hdr)) |
| 552 |
f1i = flds.index(f1) |
| 553 |
f2i = flds.index(f2) |
| 554 |
f3i = flds.index(f3) |
| 555 |
for v1, v1rows in itertools.groupby(it, key=operator.itemgetter(f1i)): |
| 556 |
outrow = [v1] + [missing] * len(f2vals) |
| 557 |
for v2, v12rows in itertools.groupby(v1rows, |
| 558 |
key=operator.itemgetter(f2i)): |
| 559 |
aggval = aggfun([row[f3i] for row in v12rows]) |
| 560 |
outrow[1 + f2vals.index(v2)] = aggval |
| 561 |
yield tuple(outrow) |
| 562 |
|
| 563 |
|
| 564 |
def flatten(table): |
| 565 |
""" |
| 566 |
Convert a table to a sequence of values in row-major order. E.g.:: |
| 567 |
|
| 568 |
>>> import petl as etl |
| 569 |
>>> table1 = [['foo', 'bar', 'baz'], |
| 570 |
... ['A', 1, True], |
| 571 |
... ['C', 7, False], |
| 572 |
... ['B', 2, False], |
| 573 |
... ['C', 9, True]] |
| 574 |
>>> list(etl.flatten(table1)) |
| 575 |
['A', 1, True, 'C', 7, False, 'B', 2, False, 'C', 9, True] |
| 576 |
|
| 577 |
See also :func:`petl.transform.reshape.unflatten`. |
| 578 |
|
| 579 |
""" |
| 580 |
|
| 581 |
return FlattenView(table) |
| 582 |
|
| 583 |
|
| 584 |
Table.flatten = flatten |
| 585 |
|
| 586 |
|
| 587 |
class FlattenView(Table): |
| 588 |
|
| 589 |
def __init__(self, table): |
| 590 |
self.table = table |
| 591 |
|
| 592 |
def __iter__(self): |
| 593 |
for row in data(self.table): |
| 594 |
for value in row: |
| 595 |
yield value |
| 596 |
|
| 597 |
|
| 598 |
def unflatten(*args, **kwargs): |
| 599 |
""" |
| 600 |
Convert a sequence of values in row-major order into a table. E.g.:: |
| 601 |
|
| 602 |
>>> import petl as etl |
| 603 |
>>> a = ['A', 1, True, 'C', 7, False, 'B', 2, False, 'C', 9] |
| 604 |
>>> table1 = etl.unflatten(a, 3) |
| 605 |
>>> table1 |
| 606 |
+-----+----+-------+ |
| 607 |
| f0 | f1 | f2 | |
| 608 |
+=====+====+=======+ |
| 609 |
| 'A' | 1 | True | |
| 610 |
+-----+----+-------+ |
| 611 |
| 'C' | 7 | False | |
| 612 |
+-----+----+-------+ |
| 613 |
| 'B' | 2 | False | |
| 614 |
+-----+----+-------+ |
| 615 |
| 'C' | 9 | None | |
| 616 |
+-----+----+-------+ |
| 617 |
|
| 618 |
>>> # a table and field name can also be provided as arguments |
| 619 |
... table2 = [['lines'], |
| 620 |
... ['A'], |
| 621 |
... [1], |
| 622 |
... [True], |
| 623 |
... ['C'], |
| 624 |
... [7], |
| 625 |
... [False], |
| 626 |
... ['B'], |
| 627 |
... [2], |
| 628 |
... [False], |
| 629 |
... ['C'], |
| 630 |
... [9]] |
| 631 |
>>> table3 = etl.unflatten(table2, 'lines', 3) |
| 632 |
>>> table3 |
| 633 |
+-----+----+-------+ |
| 634 |
| f0 | f1 | f2 | |
| 635 |
+=====+====+=======+ |
| 636 |
| 'A' | 1 | True | |
| 637 |
+-----+----+-------+ |
| 638 |
| 'C' | 7 | False | |
| 639 |
+-----+----+-------+ |
| 640 |
| 'B' | 2 | False | |
| 641 |
+-----+----+-------+ |
| 642 |
| 'C' | 9 | None | |
| 643 |
+-----+----+-------+ |
| 644 |
|
| 645 |
See also :func:`petl.transform.reshape.flatten`. |
| 646 |
|
| 647 |
""" |
| 648 |
|
| 649 |
return UnflattenView(*args, **kwargs) |
| 650 |
|
| 651 |
|
| 652 |
Table.unflatten = unflatten |
| 653 |
|
| 654 |
|
| 655 |
class UnflattenView(Table): |
| 656 |
|
| 657 |
def __init__(self, *args, **kwargs): |
| 658 |
if len(args) == 2: |
| 659 |
self.input = args[0] |
| 660 |
self.period = args[1] |
| 661 |
elif len(args) == 3: |
| 662 |
self.input = values(args[0], args[1]) |
| 663 |
self.period = args[2] |
| 664 |
else: |
| 665 |
assert False, 'invalid arguments' |
| 666 |
self.missing = kwargs.get('missing', None) |
| 667 |
|
| 668 |
def __iter__(self): |
| 669 |
inpt = self.input |
| 670 |
period = self.period |
| 671 |
missing = self.missing |
| 672 |
|
| 673 |
# generate header row |
| 674 |
outhdr = tuple('f%s' % i for i in range(period)) |
| 675 |
yield outhdr |
| 676 |
|
| 677 |
# generate data rows |
| 678 |
row = list() |
| 679 |
for v in inpt: |
| 680 |
if len(row) < period: |
| 681 |
row.append(v) |
| 682 |
else: |
| 683 |
yield tuple(row) |
| 684 |
row = [v] |
| 685 |
|
| 686 |
# deal with last row |
| 687 |
if len(row) > 0: |
| 688 |
if len(row) < period: |
| 689 |
row.extend([missing] * (period - len(row))) |
| 690 |
yield tuple(row) |