| 1 |
from __future__ import absolute_import, print_function, division |
| 2 |
|
| 3 |
|
| 4 |
import operator |
| 5 |
from petl.compat import text_type |
| 6 |
|
| 7 |
|
| 8 |
from petl.util.base import Table, asindices, itervalues |
| 9 |
from petl.transform.sorts import sort |
| 10 |
|
| 11 |
|
| 12 |
def duplicates(table, key=None, presorted=False, buffersize=None, tempdir=None, |
| 13 |
cache=True): |
| 14 |
""" |
| 15 |
Select rows with duplicate values under a given key (or duplicate |
| 16 |
rows where no key is given). E.g.:: |
| 17 |
|
| 18 |
>>> import petl as etl |
| 19 |
>>> table1 = [['foo', 'bar', 'baz'], |
| 20 |
... ['A', 1, 2.0], |
| 21 |
... ['B', 2, 3.4], |
| 22 |
... ['D', 6, 9.3], |
| 23 |
... ['B', 3, 7.8], |
| 24 |
... ['B', 2, 12.3], |
| 25 |
... ['E', None, 1.3], |
| 26 |
... ['D', 4, 14.5]] |
| 27 |
>>> table2 = etl.duplicates(table1, 'foo') |
| 28 |
>>> table2 |
| 29 |
+-----+-----+------+ |
| 30 |
| foo | bar | baz | |
| 31 |
+=====+=====+======+ |
| 32 |
| 'B' | 2 | 3.4 | |
| 33 |
+-----+-----+------+ |
| 34 |
| 'B' | 3 | 7.8 | |
| 35 |
+-----+-----+------+ |
| 36 |
| 'B' | 2 | 12.3 | |
| 37 |
+-----+-----+------+ |
| 38 |
| 'D' | 6 | 9.3 | |
| 39 |
+-----+-----+------+ |
| 40 |
| 'D' | 4 | 14.5 | |
| 41 |
+-----+-----+------+ |
| 42 |
|
| 43 |
>>> # compound keys are supported |
| 44 |
... table3 = etl.duplicates(table1, key=['foo', 'bar']) |
| 45 |
>>> table3 |
| 46 |
+-----+-----+------+ |
| 47 |
| foo | bar | baz | |
| 48 |
+=====+=====+======+ |
| 49 |
| 'B' | 2 | 3.4 | |
| 50 |
+-----+-----+------+ |
| 51 |
| 'B' | 2 | 12.3 | |
| 52 |
+-----+-----+------+ |
| 53 |
|
| 54 |
If `presorted` is True, it is assumed that the data are already sorted by |
| 55 |
the given key, and the `buffersize`, `tempdir` and `cache` arguments are |
| 56 |
ignored. Otherwise, the data are sorted, see also the discussion of the |
| 57 |
`buffersize`, `tempdir` and `cache` arguments under the |
| 58 |
:func:`petl.transform.sorts.sort` function. |
| 59 |
|
| 60 |
See also :func:`petl.transform.dedup.unique` and |
| 61 |
:func:`petl.transform.dedup.distinct`. |
| 62 |
|
| 63 |
""" |
| 64 |
|
| 65 |
return DuplicatesView(table, key=key, presorted=presorted, |
| 66 |
buffersize=buffersize, tempdir=tempdir, cache=cache) |
| 67 |
|
| 68 |
|
| 69 |
Table.duplicates = duplicates |
| 70 |
|
| 71 |
|
| 72 |
class DuplicatesView(Table): |
| 73 |
|
| 74 |
def __init__(self, source, key=None, presorted=False, buffersize=None, |
| 75 |
tempdir=None, cache=True): |
| 76 |
if presorted: |
| 77 |
self.source = source |
| 78 |
else: |
| 79 |
self.source = sort(source, key, buffersize=buffersize, |
| 80 |
tempdir=tempdir, cache=cache) |
| 81 |
self.key = key |
| 82 |
|
| 83 |
def __iter__(self): |
| 84 |
return iterduplicates(self.source, self.key) |
| 85 |
|
| 86 |
|
| 87 |
def iterduplicates(source, key): |
| 88 |
# assume source is sorted |
| 89 |
# first need to sort the data |
| 90 |
it = iter(source) |
| 91 |
|
| 92 |
try: |
| 93 |
hdr = next(it) |
| 94 |
except StopIteration: |
| 95 |
if key is None: |
| 96 |
return # nothing to do on a table without headers |
| 97 |
hdr = [] |
| 98 |
yield tuple(hdr) |
| 99 |
|
| 100 |
# convert field selection into field indices |
| 101 |
if key is None: |
| 102 |
indices = range(len(hdr)) |
| 103 |
else: |
| 104 |
indices = asindices(hdr, key) |
| 105 |
|
| 106 |
# now use field indices to construct a _getkey function |
| 107 |
# N.B., this may raise an exception on short rows, depending on |
| 108 |
# the field selection |
| 109 |
getkey = operator.itemgetter(*indices) |
| 110 |
|
| 111 |
previous = None |
| 112 |
previous_yielded = False |
| 113 |
|
| 114 |
for row in it: |
| 115 |
if previous is None: |
| 116 |
previous = row |
| 117 |
else: |
| 118 |
kprev = getkey(previous) |
| 119 |
kcurr = getkey(row) |
| 120 |
if kprev == kcurr: |
| 121 |
if not previous_yielded: |
| 122 |
yield tuple(previous) |
| 123 |
previous_yielded = True |
| 124 |
yield tuple(row) |
| 125 |
else: |
| 126 |
# reset |
| 127 |
previous_yielded = False |
| 128 |
previous = row |
| 129 |
|
| 130 |
|
| 131 |
def unique(table, key=None, presorted=False, buffersize=None, tempdir=None, |
| 132 |
cache=True): |
| 133 |
""" |
| 134 |
Select rows with unique values under a given key (or unique rows |
| 135 |
if no key is given). E.g.:: |
| 136 |
|
| 137 |
>>> import petl as etl |
| 138 |
>>> table1 = [['foo', 'bar', 'baz'], |
| 139 |
... ['A', 1, 2], |
| 140 |
... ['B', '2', '3.4'], |
| 141 |
... ['D', 'xyz', 9.0], |
| 142 |
... ['B', u'3', u'7.8'], |
| 143 |
... ['B', '2', 42], |
| 144 |
... ['E', None, None], |
| 145 |
... ['D', 4, 12.3], |
| 146 |
... ['F', 7, 2.3]] |
| 147 |
>>> table2 = etl.unique(table1, 'foo') |
| 148 |
>>> table2 |
| 149 |
+-----+------+------+ |
| 150 |
| foo | bar | baz | |
| 151 |
+=====+======+======+ |
| 152 |
| 'A' | 1 | 2 | |
| 153 |
+-----+------+------+ |
| 154 |
| 'E' | None | None | |
| 155 |
+-----+------+------+ |
| 156 |
| 'F' | 7 | 2.3 | |
| 157 |
+-----+------+------+ |
| 158 |
|
| 159 |
If `presorted` is True, it is assumed that the data are already sorted by |
| 160 |
the given key, and the `buffersize`, `tempdir` and `cache` arguments are |
| 161 |
ignored. Otherwise, the data are sorted, see also the discussion of the |
| 162 |
`buffersize`, `tempdir` and `cache` arguments under the |
| 163 |
:func:`petl.transform.sorts.sort` function. |
| 164 |
|
| 165 |
See also :func:`petl.transform.dedup.duplicates` and |
| 166 |
:func:`petl.transform.dedup.distinct`. |
| 167 |
|
| 168 |
""" |
| 169 |
|
| 170 |
return UniqueView(table, key=key, presorted=presorted, |
| 171 |
buffersize=buffersize, tempdir=tempdir, cache=cache) |
| 172 |
|
| 173 |
|
| 174 |
Table.unique = unique |
| 175 |
|
| 176 |
|
| 177 |
class UniqueView(Table): |
| 178 |
|
| 179 |
def __init__(self, source, key=None, presorted=False, buffersize=None, |
| 180 |
tempdir=None, cache=True): |
| 181 |
if presorted: |
| 182 |
self.source = source |
| 183 |
else: |
| 184 |
self.source = sort(source, key, buffersize=buffersize, |
| 185 |
tempdir=tempdir, cache=cache) |
| 186 |
self.key = key |
| 187 |
|
| 188 |
def __iter__(self): |
| 189 |
return iterunique(self.source, self.key) |
| 190 |
|
| 191 |
|
| 192 |
def iterunique(source, key): |
| 193 |
# assume source is sorted |
| 194 |
# first need to sort the data |
| 195 |
it = iter(source) |
| 196 |
|
| 197 |
try: |
| 198 |
hdr = next(it) |
| 199 |
except StopIteration: |
| 200 |
return |
| 201 |
yield tuple(hdr) |
| 202 |
|
| 203 |
# convert field selection into field indices |
| 204 |
if key is None: |
| 205 |
indices = range(len(hdr)) |
| 206 |
else: |
| 207 |
indices = asindices(hdr, key) |
| 208 |
|
| 209 |
# now use field indices to construct a _getkey function |
| 210 |
# N.B., this may raise an exception on short rows, depending on |
| 211 |
# the field selection |
| 212 |
getkey = operator.itemgetter(*indices) |
| 213 |
|
| 214 |
try: |
| 215 |
prev = next(it) |
| 216 |
except StopIteration: |
| 217 |
return |
| 218 |
|
| 219 |
prev_key = getkey(prev) |
| 220 |
prev_comp_ne = True |
| 221 |
|
| 222 |
for curr in it: |
| 223 |
curr_key = getkey(curr) |
| 224 |
curr_comp_ne = (curr_key != prev_key) |
| 225 |
if prev_comp_ne and curr_comp_ne: |
| 226 |
yield tuple(prev) |
| 227 |
prev = curr |
| 228 |
prev_key = curr_key |
| 229 |
prev_comp_ne = curr_comp_ne |
| 230 |
|
| 231 |
# last one? |
| 232 |
if prev_comp_ne: |
| 233 |
yield prev |
| 234 |
|
| 235 |
|
| 236 |
def conflicts(table, key, missing=None, include=None, exclude=None, |
| 237 |
presorted=False, buffersize=None, tempdir=None, cache=True): |
| 238 |
""" |
| 239 |
Select rows with the same key value but differing in some other field. |
| 240 |
E.g.:: |
| 241 |
|
| 242 |
>>> import petl as etl |
| 243 |
>>> table1 = [['foo', 'bar', 'baz'], |
| 244 |
... ['A', 1, 2.7], |
| 245 |
... ['B', 2, None], |
| 246 |
... ['D', 3, 9.4], |
| 247 |
... ['B', None, 7.8], |
| 248 |
... ['E', None], |
| 249 |
... ['D', 3, 12.3], |
| 250 |
... ['A', 2, None]] |
| 251 |
>>> table2 = etl.conflicts(table1, 'foo') |
| 252 |
>>> table2 |
| 253 |
+-----+-----+------+ |
| 254 |
| foo | bar | baz | |
| 255 |
+=====+=====+======+ |
| 256 |
| 'A' | 1 | 2.7 | |
| 257 |
+-----+-----+------+ |
| 258 |
| 'A' | 2 | None | |
| 259 |
+-----+-----+------+ |
| 260 |
| 'D' | 3 | 9.4 | |
| 261 |
+-----+-----+------+ |
| 262 |
| 'D' | 3 | 12.3 | |
| 263 |
+-----+-----+------+ |
| 264 |
|
| 265 |
Missing values are not considered conflicts. By default, `None` is treated |
| 266 |
as the missing value, this can be changed via the `missing` keyword |
| 267 |
argument. |
| 268 |
|
| 269 |
One or more fields can be ignored when determining conflicts by providing |
| 270 |
the `exclude` keyword argument. Alternatively, fields to use when |
| 271 |
determining conflicts can be specified explicitly with the `include` |
| 272 |
keyword argument. This provides a simple mechanism for analysing the |
| 273 |
source of conflicting rows from multiple tables, e.g.:: |
| 274 |
|
| 275 |
>>> table1 = [['foo', 'bar'], [1, 'a'], [2, 'b']] |
| 276 |
>>> table2 = [['foo', 'bar'], [1, 'a'], [2, 'c']] |
| 277 |
>>> table3 = etl.cat(etl.addfield(table1, 'source', 1), |
| 278 |
... etl.addfield(table2, 'source', 2)) |
| 279 |
>>> table4 = etl.conflicts(table3, key='foo', exclude='source') |
| 280 |
>>> table4 |
| 281 |
+-----+-----+--------+ |
| 282 |
| foo | bar | source | |
| 283 |
+=====+=====+========+ |
| 284 |
| 2 | 'b' | 1 | |
| 285 |
+-----+-----+--------+ |
| 286 |
| 2 | 'c' | 2 | |
| 287 |
+-----+-----+--------+ |
| 288 |
|
| 289 |
If `presorted` is True, it is assumed that the data are already sorted by |
| 290 |
the given key, and the `buffersize`, `tempdir` and `cache` arguments are |
| 291 |
ignored. Otherwise, the data are sorted, see also the discussion of the |
| 292 |
`buffersize`, `tempdir` and `cache` arguments under the |
| 293 |
:func:`petl.transform.sorts.sort` function. |
| 294 |
|
| 295 |
""" |
| 296 |
|
| 297 |
return ConflictsView(table, key, missing=missing, exclude=exclude, |
| 298 |
include=include, presorted=presorted, |
| 299 |
buffersize=buffersize, tempdir=tempdir, cache=cache) |
| 300 |
|
| 301 |
|
| 302 |
Table.conflicts = conflicts |
| 303 |
|
| 304 |
|
| 305 |
class ConflictsView(Table): |
| 306 |
|
| 307 |
def __init__(self, source, key, missing=None, exclude=None, include=None, |
| 308 |
presorted=False, buffersize=None, tempdir=None, cache=True): |
| 309 |
if presorted: |
| 310 |
self.source = source |
| 311 |
else: |
| 312 |
self.source = sort(source, key, buffersize=buffersize, |
| 313 |
tempdir=tempdir, cache=cache) |
| 314 |
self.key = key |
| 315 |
self.missing = missing |
| 316 |
self.exclude = exclude |
| 317 |
self.include = include |
| 318 |
|
| 319 |
def __iter__(self): |
| 320 |
return iterconflicts(self.source, self.key, self.missing, self.exclude, |
| 321 |
self.include) |
| 322 |
|
| 323 |
|
| 324 |
def iterconflicts(source, key, missing, exclude, include): |
| 325 |
|
| 326 |
# normalise arguments |
| 327 |
if exclude and not isinstance(exclude, (list, tuple)): |
| 328 |
exclude = (exclude,) |
| 329 |
if include and not isinstance(include, (list, tuple)): |
| 330 |
include = (include,) |
| 331 |
|
| 332 |
# exclude overrides include |
| 333 |
if include and exclude: |
| 334 |
include = None |
| 335 |
|
| 336 |
it = iter(source) |
| 337 |
try: |
| 338 |
hdr = next(it) |
| 339 |
except StopIteration: |
| 340 |
return |
| 341 |
flds = list(map(text_type, hdr)) |
| 342 |
yield tuple(hdr) |
| 343 |
|
| 344 |
# convert field selection into field indices |
| 345 |
indices = asindices(hdr, key) |
| 346 |
|
| 347 |
# now use field indices to construct a _getkey function |
| 348 |
# N.B., this may raise an exception on short rows, depending on |
| 349 |
# the field selection |
| 350 |
getkey = operator.itemgetter(*indices) |
| 351 |
|
| 352 |
previous = None |
| 353 |
previous_yielded = False |
| 354 |
|
| 355 |
for row in it: |
| 356 |
if previous is None: |
| 357 |
previous = row |
| 358 |
else: |
| 359 |
kprev = getkey(previous) |
| 360 |
kcurr = getkey(row) |
| 361 |
if kprev == kcurr: |
| 362 |
# is there a conflict? |
| 363 |
conflict = False |
| 364 |
for x, y, f in zip(previous, row, flds): |
| 365 |
if (exclude and f not in exclude) \ |
| 366 |
or (include and f in include) \ |
| 367 |
or (not exclude and not include): |
| 368 |
if missing not in (x, y) and x != y: |
| 369 |
conflict = True |
| 370 |
break |
| 371 |
if conflict: |
| 372 |
if not previous_yielded: |
| 373 |
yield tuple(previous) |
| 374 |
previous_yielded = True |
| 375 |
yield tuple(row) |
| 376 |
else: |
| 377 |
# reset |
| 378 |
previous_yielded = False |
| 379 |
previous = row |
| 380 |
|
| 381 |
|
| 382 |
def distinct(table, key=None, count=None, presorted=False, buffersize=None, |
| 383 |
tempdir=None, cache=True): |
| 384 |
""" |
| 385 |
Return only distinct rows in the table. |
| 386 |
|
| 387 |
If the `count` argument is not None, it will be used as the name for an |
| 388 |
additional field, and the values of the field will be the number of |
| 389 |
duplicate rows. |
| 390 |
|
| 391 |
If the `key` keyword argument is passed, the comparison is done on the |
| 392 |
given key instead of the full row. |
| 393 |
|
| 394 |
See also :func:`petl.transform.dedup.duplicates`, |
| 395 |
:func:`petl.transform.dedup.unique`, |
| 396 |
:func:`petl.transform.reductions.groupselectfirst`, |
| 397 |
:func:`petl.transform.reductions.groupselectlast`. |
| 398 |
|
| 399 |
""" |
| 400 |
|
| 401 |
return DistinctView(table, key=key, count=count, presorted=presorted, |
| 402 |
buffersize=buffersize, tempdir=tempdir, cache=cache) |
| 403 |
|
| 404 |
|
| 405 |
Table.distinct = distinct |
| 406 |
|
| 407 |
|
| 408 |
class DistinctView(Table): |
| 409 |
def __init__(self, table, key=None, count=None, presorted=False, |
| 410 |
buffersize=None, tempdir=None, cache=True): |
| 411 |
if presorted: |
| 412 |
self.table = table |
| 413 |
else: |
| 414 |
self.table = sort(table, key=key, buffersize=buffersize, |
| 415 |
tempdir=tempdir, cache=cache) |
| 416 |
self.key = key |
| 417 |
self.count = count |
| 418 |
|
| 419 |
def __iter__(self): |
| 420 |
it = iter(self.table) |
| 421 |
try: |
| 422 |
hdr = next(it) |
| 423 |
except StopIteration: |
| 424 |
return |
| 425 |
|
| 426 |
# convert field selection into field indices |
| 427 |
if self.key is None: |
| 428 |
indices = range(len(hdr)) |
| 429 |
else: |
| 430 |
indices = asindices(hdr, self.key) |
| 431 |
|
| 432 |
# now use field indices to construct a _getkey function |
| 433 |
# N.B., this may raise an exception on short rows, depending on |
| 434 |
# the field selection |
| 435 |
getkey = operator.itemgetter(*indices) |
| 436 |
|
| 437 |
INIT = object() |
| 438 |
if self.count: |
| 439 |
hdr = tuple(hdr) + (self.count,) |
| 440 |
yield hdr |
| 441 |
previous = INIT |
| 442 |
n_dup = 1 |
| 443 |
for row in it: |
| 444 |
if previous is INIT: |
| 445 |
previous = row |
| 446 |
else: |
| 447 |
kprev = getkey(previous) |
| 448 |
kcurr = getkey(row) |
| 449 |
if kprev == kcurr: |
| 450 |
n_dup += 1 |
| 451 |
else: |
| 452 |
yield tuple(previous) + (n_dup,) |
| 453 |
n_dup = 1 |
| 454 |
previous = row |
| 455 |
# deal with last row |
| 456 |
yield tuple(previous) + (n_dup,) |
| 457 |
else: |
| 458 |
yield tuple(hdr) |
| 459 |
previous_keys = INIT |
| 460 |
for row in it: |
| 461 |
keys = getkey(row) |
| 462 |
if keys != previous_keys: |
| 463 |
yield tuple(row) |
| 464 |
previous_keys = keys |
| 465 |
|
| 466 |
|
| 467 |
def isunique(table, field): |
| 468 |
""" |
| 469 |
Return True if there are no duplicate values for the given field(s), |
| 470 |
otherwise False. E.g.:: |
| 471 |
|
| 472 |
>>> import petl as etl |
| 473 |
>>> table1 = [['foo', 'bar'], |
| 474 |
... ['a', 1], |
| 475 |
... ['b'], |
| 476 |
... ['b', 2], |
| 477 |
... ['c', 3, True]] |
| 478 |
>>> etl.isunique(table1, 'foo') |
| 479 |
False |
| 480 |
>>> etl.isunique(table1, 'bar') |
| 481 |
True |
| 482 |
|
| 483 |
The `field` argument can be a single field name or index (starting from |
| 484 |
zero) or a tuple of field names and/or indexes. |
| 485 |
|
| 486 |
""" |
| 487 |
|
| 488 |
vals = set() |
| 489 |
for v in itervalues(table, field): |
| 490 |
if v in vals: |
| 491 |
return False |
| 492 |
else: |
| 493 |
vals.add(v) |
| 494 |
return True |
| 495 |
|
| 496 |
|
| 497 |
Table.isunique = isunique |