| 1 |
from __future__ import absolute_import, print_function, division |
| 2 |
|
| 3 |
|
| 4 |
from collections import Counter |
| 5 |
from petl.compat import string_types, maketrans |
| 6 |
|
| 7 |
|
| 8 |
from petl.util.base import values, Table, data, wrap |
| 9 |
|
| 10 |
|
| 11 |
def nrows(table): |
| 12 |
""" |
| 13 |
Count the number of data rows in a table. E.g.:: |
| 14 |
|
| 15 |
>>> import petl as etl |
| 16 |
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2]] |
| 17 |
>>> etl.nrows(table) |
| 18 |
2 |
| 19 |
|
| 20 |
""" |
| 21 |
|
| 22 |
return sum(1 for _ in data(table)) |
| 23 |
|
| 24 |
|
| 25 |
Table.nrows = nrows |
| 26 |
|
| 27 |
|
| 28 |
def valuecount(table, field, value, missing=None): |
| 29 |
""" |
| 30 |
Count the number of occurrences of `value` under the given field. Returns |
| 31 |
the absolute count and relative frequency as a pair. E.g.:: |
| 32 |
|
| 33 |
>>> import petl as etl |
| 34 |
>>> table = [['foo', 'bar'], |
| 35 |
... ['a', 1], |
| 36 |
... ['b', 2], |
| 37 |
... ['b', 7]] |
| 38 |
>>> etl.valuecount(table, 'foo', 'b') |
| 39 |
(2, 0.6666666666666666) |
| 40 |
|
| 41 |
The `field` argument can be a single field name or index (starting from |
| 42 |
zero) or a tuple of field names and/or indexes. |
| 43 |
|
| 44 |
""" |
| 45 |
|
| 46 |
total = 0 |
| 47 |
vs = 0 |
| 48 |
for v in values(table, field, missing=missing): |
| 49 |
total += 1 |
| 50 |
if v == value: |
| 51 |
vs += 1 |
| 52 |
return vs, float(vs)/total |
| 53 |
|
| 54 |
|
| 55 |
Table.valuecount = valuecount |
| 56 |
|
| 57 |
|
| 58 |
def valuecounter(table, *field, **kwargs): |
| 59 |
""" |
| 60 |
Find distinct values for the given field and count the number of |
| 61 |
occurrences. Returns a :class:`dict` mapping values to counts. E.g.:: |
| 62 |
|
| 63 |
>>> import petl as etl |
| 64 |
>>> table = [['foo', 'bar'], |
| 65 |
... ['a', True], |
| 66 |
... ['b'], |
| 67 |
... ['b', True], |
| 68 |
... ['c', False]] |
| 69 |
>>> etl.valuecounter(table, 'foo') |
| 70 |
Counter({'b': 2, 'a': 1, 'c': 1}) |
| 71 |
|
| 72 |
The `field` argument can be a single field name or index (starting from |
| 73 |
zero) or a tuple of field names and/or indexes. |
| 74 |
|
| 75 |
""" |
| 76 |
|
| 77 |
missing = kwargs.get('missing', None) |
| 78 |
counter = Counter() |
| 79 |
for v in values(table, field, missing=missing): |
| 80 |
try: |
| 81 |
counter[v] += 1 |
| 82 |
except IndexError: |
| 83 |
pass # short row |
| 84 |
return counter |
| 85 |
|
| 86 |
|
| 87 |
Table.valuecounter = valuecounter |
| 88 |
|
| 89 |
|
| 90 |
def valuecounts(table, *field, **kwargs): |
| 91 |
""" |
| 92 |
Find distinct values for the given field and count the number and relative |
| 93 |
frequency of occurrences. Returns a table mapping values to counts, with |
| 94 |
most common values first. E.g.:: |
| 95 |
|
| 96 |
>>> import petl as etl |
| 97 |
>>> table = [['foo', 'bar', 'baz'], |
| 98 |
... ['a', True, 0.12], |
| 99 |
... ['a', True, 0.17], |
| 100 |
... ['b', False, 0.34], |
| 101 |
... ['b', False, 0.44], |
| 102 |
... ['b']] |
| 103 |
>>> etl.valuecounts(table, 'foo') |
| 104 |
+-----+-------+-----------+ |
| 105 |
| foo | count | frequency | |
| 106 |
+=====+=======+===========+ |
| 107 |
| 'b' | 3 | 0.6 | |
| 108 |
+-----+-------+-----------+ |
| 109 |
| 'a' | 2 | 0.4 | |
| 110 |
+-----+-------+-----------+ |
| 111 |
|
| 112 |
>>> etl.valuecounts(table, 'foo', 'bar') |
| 113 |
+-----+-------+-------+-----------+ |
| 114 |
| foo | bar | count | frequency | |
| 115 |
+=====+=======+=======+===========+ |
| 116 |
| 'a' | True | 2 | 0.4 | |
| 117 |
+-----+-------+-------+-----------+ |
| 118 |
| 'b' | False | 2 | 0.4 | |
| 119 |
+-----+-------+-------+-----------+ |
| 120 |
| 'b' | None | 1 | 0.2 | |
| 121 |
+-----+-------+-------+-----------+ |
| 122 |
|
| 123 |
If rows are short, the value of the keyword argument `missing` is counted. |
| 124 |
|
| 125 |
Multiple fields can be given as positional arguments. If multiple fields are |
| 126 |
given, these are treated as a compound key. |
| 127 |
|
| 128 |
""" |
| 129 |
|
| 130 |
return ValueCountsView(table, field, **kwargs) |
| 131 |
|
| 132 |
|
| 133 |
Table.valuecounts = valuecounts |
| 134 |
|
| 135 |
|
| 136 |
class ValueCountsView(Table): |
| 137 |
|
| 138 |
def __init__(self, table, field, missing=None): |
| 139 |
self.table = table |
| 140 |
self.field = field |
| 141 |
self.missing = missing |
| 142 |
|
| 143 |
def __iter__(self): |
| 144 |
|
| 145 |
# construct output header |
| 146 |
if isinstance(self.field, (tuple, list)): |
| 147 |
outhdr = tuple(self.field) + ('count', 'frequency') |
| 148 |
else: |
| 149 |
outhdr = (self.field, 'count', 'frequency') |
| 150 |
yield outhdr |
| 151 |
|
| 152 |
# count values |
| 153 |
counter = valuecounter(self.table, *self.field, missing=self.missing) |
| 154 |
counts = counter.most_common() # sort descending |
| 155 |
total = sum(c[1] for c in counts) |
| 156 |
|
| 157 |
if len(self.field) > 1: |
| 158 |
for c in counts: |
| 159 |
yield tuple(c[0]) + (c[1], float(c[1])/total) |
| 160 |
else: |
| 161 |
for c in counts: |
| 162 |
yield (c[0], c[1], float(c[1])/total) |
| 163 |
|
| 164 |
|
| 165 |
def parsecounter(table, field, parsers=(('int', int), ('float', float))): |
| 166 |
""" |
| 167 |
Count the number of `str` or `unicode` values under the given fields that |
| 168 |
can be parsed as ints, floats or via custom parser functions. Return a |
| 169 |
pair of `Counter` objects, the first mapping parser names to the number of |
| 170 |
strings successfully parsed, the second mapping parser names to the |
| 171 |
number of errors. E.g.:: |
| 172 |
|
| 173 |
>>> import petl as etl |
| 174 |
>>> table = [['foo', 'bar', 'baz'], |
| 175 |
... ['A', 'aaa', 2], |
| 176 |
... ['B', u'2', '3.4'], |
| 177 |
... [u'B', u'3', u'7.8', True], |
| 178 |
... ['D', '3.7', 9.0], |
| 179 |
... ['E', 42]] |
| 180 |
>>> counter, errors = etl.parsecounter(table, 'bar') |
| 181 |
>>> counter |
| 182 |
Counter({'float': 3, 'int': 2}) |
| 183 |
>>> errors |
| 184 |
Counter({'int': 2, 'float': 1}) |
| 185 |
|
| 186 |
The `field` argument can be a field name or index (starting from zero). |
| 187 |
|
| 188 |
""" |
| 189 |
|
| 190 |
if isinstance(parsers, (list, tuple)): |
| 191 |
parsers = dict(parsers) |
| 192 |
counter, errors = Counter(), Counter() |
| 193 |
# need to initialise |
| 194 |
for n in parsers.keys(): |
| 195 |
counter[n] = 0 |
| 196 |
errors[n] = 0 |
| 197 |
for v in values(table, field): |
| 198 |
if isinstance(v, string_types): |
| 199 |
for name, parser in parsers.items(): |
| 200 |
try: |
| 201 |
parser(v) |
| 202 |
except: |
| 203 |
errors[name] += 1 |
| 204 |
else: |
| 205 |
counter[name] += 1 |
| 206 |
return counter, errors |
| 207 |
|
| 208 |
|
| 209 |
Table.parsecounter = parsecounter |
| 210 |
|
| 211 |
|
| 212 |
def parsecounts(table, field, parsers=(('int', int), ('float', float))): |
| 213 |
""" |
| 214 |
Count the number of `str` or `unicode` values that can be parsed as ints, |
| 215 |
floats or via custom parser functions. Return a table mapping parser names |
| 216 |
to the number of values successfully parsed and the number of errors. E.g.:: |
| 217 |
|
| 218 |
>>> import petl as etl |
| 219 |
>>> table = [['foo', 'bar', 'baz'], |
| 220 |
... ['A', 'aaa', 2], |
| 221 |
... ['B', u'2', '3.4'], |
| 222 |
... [u'B', u'3', u'7.8', True], |
| 223 |
... ['D', '3.7', 9.0], |
| 224 |
... ['E', 42]] |
| 225 |
>>> etl.parsecounts(table, 'bar') |
| 226 |
+---------+-------+--------+ |
| 227 |
| type | count | errors | |
| 228 |
+=========+=======+========+ |
| 229 |
| 'float' | 3 | 1 | |
| 230 |
+---------+-------+--------+ |
| 231 |
| 'int' | 2 | 2 | |
| 232 |
+---------+-------+--------+ |
| 233 |
|
| 234 |
The `field` argument can be a field name or index (starting from zero). |
| 235 |
|
| 236 |
""" |
| 237 |
|
| 238 |
return ParseCountsView(table, field, parsers=parsers) |
| 239 |
|
| 240 |
|
| 241 |
Table.parsecounts = parsecounts |
| 242 |
|
| 243 |
|
| 244 |
class ParseCountsView(Table): |
| 245 |
|
| 246 |
def __init__(self, table, field, parsers=(('int', int), ('float', float))): |
| 247 |
self.table = table |
| 248 |
self.field = field |
| 249 |
if isinstance(parsers, (list, tuple)): |
| 250 |
parsers = dict(parsers) |
| 251 |
self.parsers = parsers |
| 252 |
|
| 253 |
def __iter__(self): |
| 254 |
counter, errors = parsecounter(self.table, self.field, self.parsers) |
| 255 |
yield ('type', 'count', 'errors') |
| 256 |
for (item, n) in counter.most_common(): |
| 257 |
yield (item, n, errors[item]) |
| 258 |
|
| 259 |
|
| 260 |
def typecounter(table, field): |
| 261 |
""" |
| 262 |
Count the number of values found for each Python type. |
| 263 |
|
| 264 |
>>> import petl as etl |
| 265 |
>>> table = [['foo', 'bar', 'baz'], |
| 266 |
... ['A', 1, 2], |
| 267 |
... ['B', u'2', '3.4'], |
| 268 |
... [u'B', u'3', u'7.8', True], |
| 269 |
... ['D', u'xyz', 9.0], |
| 270 |
... ['E', 42]] |
| 271 |
>>> etl.typecounter(table, 'foo') |
| 272 |
Counter({'str': 5}) |
| 273 |
>>> etl.typecounter(table, 'bar') |
| 274 |
Counter({'str': 3, 'int': 2}) |
| 275 |
>>> etl.typecounter(table, 'baz') |
| 276 |
Counter({'str': 2, 'int': 1, 'float': 1, 'NoneType': 1}) |
| 277 |
|
| 278 |
The `field` argument can be a field name or index (starting from zero). |
| 279 |
|
| 280 |
""" |
| 281 |
|
| 282 |
counter = Counter() |
| 283 |
for v in values(table, field): |
| 284 |
try: |
| 285 |
counter[v.__class__.__name__] += 1 |
| 286 |
except IndexError: |
| 287 |
pass # ignore short rows |
| 288 |
return counter |
| 289 |
|
| 290 |
|
| 291 |
Table.typecounter = typecounter |
| 292 |
|
| 293 |
|
| 294 |
def typecounts(table, field): |
| 295 |
""" |
| 296 |
Count the number of values found for each Python type and return a table |
| 297 |
mapping class names to counts and frequencies. E.g.:: |
| 298 |
|
| 299 |
>>> import petl as etl |
| 300 |
>>> table = [['foo', 'bar', 'baz'], |
| 301 |
... [b'A', 1, 2], |
| 302 |
... [b'B', '2', b'3.4'], |
| 303 |
... ['B', '3', '7.8', True], |
| 304 |
... ['D', u'xyz', 9.0], |
| 305 |
... ['E', 42]] |
| 306 |
>>> etl.typecounts(table, 'foo') |
| 307 |
+---------+-------+-----------+ |
| 308 |
| type | count | frequency | |
| 309 |
+=========+=======+===========+ |
| 310 |
| 'str' | 3 | 0.6 | |
| 311 |
+---------+-------+-----------+ |
| 312 |
| 'bytes' | 2 | 0.4 | |
| 313 |
+---------+-------+-----------+ |
| 314 |
|
| 315 |
>>> etl.typecounts(table, 'bar') |
| 316 |
+-------+-------+-----------+ |
| 317 |
| type | count | frequency | |
| 318 |
+=======+=======+===========+ |
| 319 |
| 'str' | 3 | 0.6 | |
| 320 |
+-------+-------+-----------+ |
| 321 |
| 'int' | 2 | 0.4 | |
| 322 |
+-------+-------+-----------+ |
| 323 |
|
| 324 |
>>> etl.typecounts(table, 'baz') |
| 325 |
+------------+-------+-----------+ |
| 326 |
| type | count | frequency | |
| 327 |
+============+=======+===========+ |
| 328 |
| 'int' | 1 | 0.2 | |
| 329 |
+------------+-------+-----------+ |
| 330 |
| 'bytes' | 1 | 0.2 | |
| 331 |
+------------+-------+-----------+ |
| 332 |
| 'str' | 1 | 0.2 | |
| 333 |
+------------+-------+-----------+ |
| 334 |
| 'float' | 1 | 0.2 | |
| 335 |
+------------+-------+-----------+ |
| 336 |
| 'NoneType' | 1 | 0.2 | |
| 337 |
+------------+-------+-----------+ |
| 338 |
|
| 339 |
The `field` argument can be a field name or index (starting from zero). |
| 340 |
|
| 341 |
""" |
| 342 |
|
| 343 |
return TypeCountsView(table, field) |
| 344 |
|
| 345 |
|
| 346 |
Table.typecounts = typecounts |
| 347 |
|
| 348 |
|
| 349 |
class TypeCountsView(Table): |
| 350 |
|
| 351 |
def __init__(self, table, field): |
| 352 |
self.table = table |
| 353 |
self.field = field |
| 354 |
|
| 355 |
def __iter__(self): |
| 356 |
counter = typecounter(self.table, self.field) |
| 357 |
yield ('type', 'count', 'frequency') |
| 358 |
counts = counter.most_common() |
| 359 |
total = sum(c[1] for c in counts) |
| 360 |
for c in counts: |
| 361 |
yield (c[0], c[1], float(c[1])/total) |
| 362 |
|
| 363 |
|
| 364 |
def stringpatterncounter(table, field): |
| 365 |
""" |
| 366 |
Profile string patterns in the given field, returning a :class:`dict` |
| 367 |
mapping patterns to counts. |
| 368 |
|
| 369 |
""" |
| 370 |
|
| 371 |
trans = maketrans( |
| 372 |
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', |
| 373 |
'AAAAAAAAAAAAAAAAAAAAAAAAAAaaaaaaaaaaaaaaaaaaaaaaaaaa9999999999' |
| 374 |
) |
| 375 |
counter = Counter() |
| 376 |
for v in values(table, field): |
| 377 |
p = str(v).translate(trans) |
| 378 |
counter[p] += 1 |
| 379 |
return counter |
| 380 |
|
| 381 |
|
| 382 |
Table.stringpatterncounter = stringpatterncounter |
| 383 |
|
| 384 |
|
| 385 |
def stringpatterns(table, field): |
| 386 |
""" |
| 387 |
Profile string patterns in the given field, returning a table of patterns, |
| 388 |
counts and frequencies. E.g.:: |
| 389 |
|
| 390 |
>>> import petl as etl |
| 391 |
>>> table = [['foo', 'bar'], |
| 392 |
... ['Mr. Foo', '123-1254'], |
| 393 |
... ['Mrs. Bar', '234-1123'], |
| 394 |
... ['Mr. Spo', '123-1254'], |
| 395 |
... [u'Mr. Baz', u'321 1434'], |
| 396 |
... [u'Mrs. Baz', u'321 1434'], |
| 397 |
... ['Mr. Quux', '123-1254-XX']] |
| 398 |
>>> etl.stringpatterns(table, 'foo') |
| 399 |
+------------+-------+---------------------+ |
| 400 |
| pattern | count | frequency | |
| 401 |
+============+=======+=====================+ |
| 402 |
| 'Aa. Aaa' | 3 | 0.5 | |
| 403 |
+------------+-------+---------------------+ |
| 404 |
| 'Aaa. Aaa' | 2 | 0.3333333333333333 | |
| 405 |
+------------+-------+---------------------+ |
| 406 |
| 'Aa. Aaaa' | 1 | 0.16666666666666666 | |
| 407 |
+------------+-------+---------------------+ |
| 408 |
|
| 409 |
>>> etl.stringpatterns(table, 'bar') |
| 410 |
+---------------+-------+---------------------+ |
| 411 |
| pattern | count | frequency | |
| 412 |
+===============+=======+=====================+ |
| 413 |
| '999-9999' | 3 | 0.5 | |
| 414 |
+---------------+-------+---------------------+ |
| 415 |
| '999 9999' | 2 | 0.3333333333333333 | |
| 416 |
+---------------+-------+---------------------+ |
| 417 |
| '999-9999-AA' | 1 | 0.16666666666666666 | |
| 418 |
+---------------+-------+---------------------+ |
| 419 |
|
| 420 |
""" |
| 421 |
|
| 422 |
counter = stringpatterncounter(table, field) |
| 423 |
output = [('pattern', 'count', 'frequency')] |
| 424 |
counter = counter.most_common() |
| 425 |
total = sum(c[1] for c in counter) |
| 426 |
cnts = [(c[0], c[1], float(c[1])/total) for c in counter] |
| 427 |
output.extend(cnts) |
| 428 |
return wrap(output) |
| 429 |
|
| 430 |
|
| 431 |
Table.stringpatterns = stringpatterns |
| 432 |
|
| 433 |
|
| 434 |
def rowlengths(table): |
| 435 |
""" |
| 436 |
Report on row lengths found in the table. E.g.:: |
| 437 |
|
| 438 |
>>> import petl as etl |
| 439 |
>>> table = [['foo', 'bar', 'baz'], |
| 440 |
... ['A', 1, 2], |
| 441 |
... ['B', '2', '3.4'], |
| 442 |
... [u'B', u'3', u'7.8', True], |
| 443 |
... ['D', 'xyz', 9.0], |
| 444 |
... ['E', None], |
| 445 |
... ['F', 9]] |
| 446 |
>>> etl.rowlengths(table) |
| 447 |
+--------+-------+ |
| 448 |
| length | count | |
| 449 |
+========+=======+ |
| 450 |
| 3 | 3 | |
| 451 |
+--------+-------+ |
| 452 |
| 2 | 2 | |
| 453 |
+--------+-------+ |
| 454 |
| 4 | 1 | |
| 455 |
+--------+-------+ |
| 456 |
|
| 457 |
Useful for finding potential problems in data files. |
| 458 |
|
| 459 |
""" |
| 460 |
|
| 461 |
counter = Counter() |
| 462 |
for row in data(table): |
| 463 |
counter[len(row)] += 1 |
| 464 |
output = [('length', 'count')] |
| 465 |
output.extend(counter.most_common()) |
| 466 |
return wrap(output) |
| 467 |
|
| 468 |
|
| 469 |
Table.rowlengths = rowlengths |