| 1 |
from __future__ import absolute_import, print_function, division |
| 2 |
|
| 3 |
|
| 4 |
import itertools |
| 5 |
from petl.compat import next, text_type |
| 6 |
from petl.errors import FieldSelectionError |
| 7 |
|
| 8 |
|
| 9 |
from petl.util.base import Table, asindices, rowgetter |
| 10 |
|
| 11 |
|
| 12 |
def rename(table, *args, **kwargs): |
| 13 |
""" |
| 14 |
Replace one or more values in the table's header row. E.g.:: |
| 15 |
|
| 16 |
>>> import petl as etl |
| 17 |
>>> table1 = [['sex', 'age'], |
| 18 |
... ['m', 12], |
| 19 |
... ['f', 34], |
| 20 |
... ['-', 56]] |
| 21 |
>>> # rename a single field |
| 22 |
... table2 = etl.rename(table1, 'sex', 'gender') |
| 23 |
>>> table2 |
| 24 |
+--------+-----+ |
| 25 |
| gender | age | |
| 26 |
+========+=====+ |
| 27 |
| 'm' | 12 | |
| 28 |
+--------+-----+ |
| 29 |
| 'f' | 34 | |
| 30 |
+--------+-----+ |
| 31 |
| '-' | 56 | |
| 32 |
+--------+-----+ |
| 33 |
|
| 34 |
>>> # rename multiple fields by passing dictionary as second argument |
| 35 |
... table3 = etl.rename(table1, {'sex': 'gender', 'age': 'age_years'}) |
| 36 |
>>> table3 |
| 37 |
+--------+-----------+ |
| 38 |
| gender | age_years | |
| 39 |
+========+===========+ |
| 40 |
| 'm' | 12 | |
| 41 |
+--------+-----------+ |
| 42 |
| 'f' | 34 | |
| 43 |
+--------+-----------+ |
| 44 |
| '-' | 56 | |
| 45 |
+--------+-----------+ |
| 46 |
|
| 47 |
The field to rename can be specified as an index (i.e., integer representing |
| 48 |
field position). |
| 49 |
|
| 50 |
If any nonexistent fields are specified, the default behaviour is to raise |
| 51 |
a `FieldSelectionError`. However, if `strict` keyword argument is `False`, any |
| 52 |
nonexistent fields specified will be silently ignored. |
| 53 |
""" |
| 54 |
|
| 55 |
return RenameView(table, *args, **kwargs) |
| 56 |
|
| 57 |
|
| 58 |
Table.rename = rename |
| 59 |
|
| 60 |
|
| 61 |
class RenameView(Table): |
| 62 |
|
| 63 |
def __init__(self, table, *args, **kwargs): |
| 64 |
self.source = table |
| 65 |
if len(args) == 0: |
| 66 |
self.spec = dict() |
| 67 |
elif len(args) == 1: |
| 68 |
self.spec = args[0] |
| 69 |
elif len(args) == 2: |
| 70 |
self.spec = {args[0]: args[1]} |
| 71 |
self.strict = kwargs.get('strict', True) |
| 72 |
|
| 73 |
def __iter__(self): |
| 74 |
return iterrename(self.source, self.spec, self.strict) |
| 75 |
|
| 76 |
def __setitem__(self, key, value): |
| 77 |
self.spec[key] = value |
| 78 |
|
| 79 |
|
| 80 |
def iterrename(source, spec, strict): |
| 81 |
it = iter(source) |
| 82 |
try: |
| 83 |
hdr = next(it) |
| 84 |
except StopIteration: |
| 85 |
hdr = [] |
| 86 |
flds = list(map(text_type, hdr)) |
| 87 |
if strict: |
| 88 |
for x in spec: |
| 89 |
if isinstance(x, int): |
| 90 |
if x < 0 or x >= len(hdr): |
| 91 |
raise FieldSelectionError(x) |
| 92 |
elif x not in flds: |
| 93 |
raise FieldSelectionError(x) |
| 94 |
outhdr = [spec[i] if i in spec |
| 95 |
else spec[f] if f in spec |
| 96 |
else f |
| 97 |
for i, f in enumerate(flds)] |
| 98 |
yield tuple(outhdr) |
| 99 |
for row in it: |
| 100 |
yield tuple(row) |
| 101 |
|
| 102 |
|
| 103 |
def setheader(table, header): |
| 104 |
""" |
| 105 |
Replace header row in the given table. E.g.:: |
| 106 |
|
| 107 |
>>> import petl as etl |
| 108 |
>>> table1 = [['foo', 'bar'], |
| 109 |
... ['a', 1], |
| 110 |
... ['b', 2]] |
| 111 |
>>> table2 = etl.setheader(table1, ['foofoo', 'barbar']) |
| 112 |
>>> table2 |
| 113 |
+--------+--------+ |
| 114 |
| foofoo | barbar | |
| 115 |
+========+========+ |
| 116 |
| 'a' | 1 | |
| 117 |
+--------+--------+ |
| 118 |
| 'b' | 2 | |
| 119 |
+--------+--------+ |
| 120 |
|
| 121 |
See also :func:`petl.transform.headers.extendheader`, |
| 122 |
:func:`petl.transform.headers.pushheader`. |
| 123 |
|
| 124 |
""" |
| 125 |
|
| 126 |
return SetHeaderView(table, header) |
| 127 |
|
| 128 |
|
| 129 |
Table.setheader = setheader |
| 130 |
|
| 131 |
|
| 132 |
class SetHeaderView(Table): |
| 133 |
|
| 134 |
def __init__(self, source, header): |
| 135 |
self.source = source |
| 136 |
self.header = header |
| 137 |
|
| 138 |
def __iter__(self): |
| 139 |
return itersetheader(self.source, self.header) |
| 140 |
|
| 141 |
|
| 142 |
def itersetheader(source, header): |
| 143 |
it = iter(source) |
| 144 |
try: |
| 145 |
next(it) # discard source header |
| 146 |
except StopIteration: |
| 147 |
pass # no previous header |
| 148 |
yield tuple(header) |
| 149 |
for row in it: |
| 150 |
yield tuple(row) |
| 151 |
|
| 152 |
|
| 153 |
def extendheader(table, fields): |
| 154 |
""" |
| 155 |
Extend header row in the given table. E.g.:: |
| 156 |
|
| 157 |
>>> import petl as etl |
| 158 |
>>> table1 = [['foo'], |
| 159 |
... ['a', 1, True], |
| 160 |
... ['b', 2, False]] |
| 161 |
>>> table2 = etl.extendheader(table1, ['bar', 'baz']) |
| 162 |
>>> table2 |
| 163 |
+-----+-----+-------+ |
| 164 |
| foo | bar | baz | |
| 165 |
+=====+=====+=======+ |
| 166 |
| 'a' | 1 | True | |
| 167 |
+-----+-----+-------+ |
| 168 |
| 'b' | 2 | False | |
| 169 |
+-----+-----+-------+ |
| 170 |
|
| 171 |
See also :func:`petl.transform.headers.setheader`, |
| 172 |
:func:`petl.transform.headers.pushheader`. |
| 173 |
|
| 174 |
""" |
| 175 |
|
| 176 |
return ExtendHeaderView(table, fields) |
| 177 |
|
| 178 |
|
| 179 |
Table.extendheader = extendheader |
| 180 |
|
| 181 |
|
| 182 |
class ExtendHeaderView(Table): |
| 183 |
|
| 184 |
def __init__(self, source, fields): |
| 185 |
self.source = source |
| 186 |
self.fields = fields |
| 187 |
|
| 188 |
def __iter__(self): |
| 189 |
return iterextendheader(self.source, self.fields) |
| 190 |
|
| 191 |
|
| 192 |
def iterextendheader(source, fields): |
| 193 |
it = iter(source) |
| 194 |
try: |
| 195 |
hdr = next(it) |
| 196 |
except StopIteration: |
| 197 |
hdr = [] |
| 198 |
outhdr = list(hdr) |
| 199 |
outhdr.extend(fields) |
| 200 |
yield tuple(outhdr) |
| 201 |
for row in it: |
| 202 |
yield tuple(row) |
| 203 |
|
| 204 |
|
| 205 |
def pushheader(table, header, *args): |
| 206 |
""" |
| 207 |
Push rows down and prepend a header row. E.g.:: |
| 208 |
|
| 209 |
>>> import petl as etl |
| 210 |
>>> table1 = [['a', 1], |
| 211 |
... ['b', 2]] |
| 212 |
>>> table2 = etl.pushheader(table1, ['foo', 'bar']) |
| 213 |
>>> table2 |
| 214 |
+-----+-----+ |
| 215 |
| foo | bar | |
| 216 |
+=====+=====+ |
| 217 |
| 'a' | 1 | |
| 218 |
+-----+-----+ |
| 219 |
| 'b' | 2 | |
| 220 |
+-----+-----+ |
| 221 |
|
| 222 |
The header row can either be a list or positional arguments. |
| 223 |
|
| 224 |
""" |
| 225 |
|
| 226 |
return PushHeaderView(table, header, *args) |
| 227 |
|
| 228 |
|
| 229 |
Table.pushheader = pushheader |
| 230 |
|
| 231 |
|
| 232 |
class PushHeaderView(Table): |
| 233 |
|
| 234 |
def __init__(self, source, header, *args): |
| 235 |
self.source = source |
| 236 |
self.args = args |
| 237 |
# if user passes header as a list, just use this and ignore args |
| 238 |
if isinstance(header, (list, tuple)): |
| 239 |
self.header = header |
| 240 |
# otherwise, |
| 241 |
elif len(args) > 0: |
| 242 |
self.header = [] |
| 243 |
self.header.append(header) # first argument is named header |
| 244 |
self.header.extend(args) # add the other positional arguments |
| 245 |
else: |
| 246 |
assert False, 'bad parameters' |
| 247 |
|
| 248 |
def __iter__(self): |
| 249 |
return iterpushheader(self.source, self.header) |
| 250 |
|
| 251 |
|
| 252 |
def iterpushheader(source, header): |
| 253 |
it = iter(source) |
| 254 |
yield tuple(header) |
| 255 |
for row in it: |
| 256 |
yield tuple(row) |
| 257 |
|
| 258 |
|
| 259 |
def skip(table, n): |
| 260 |
""" |
| 261 |
Skip `n` rows, including the header row. E.g.:: |
| 262 |
|
| 263 |
>>> import petl as etl |
| 264 |
>>> table1 = [['#aaa', 'bbb', 'ccc'], |
| 265 |
... ['#mmm'], |
| 266 |
... ['foo', 'bar'], |
| 267 |
... ['a', 1], |
| 268 |
... ['b', 2]] |
| 269 |
>>> table2 = etl.skip(table1, 2) |
| 270 |
>>> table2 |
| 271 |
+-----+-----+ |
| 272 |
| foo | bar | |
| 273 |
+=====+=====+ |
| 274 |
| 'a' | 1 | |
| 275 |
+-----+-----+ |
| 276 |
| 'b' | 2 | |
| 277 |
+-----+-----+ |
| 278 |
|
| 279 |
See also :func:`petl.transform.basics.skipcomments`. |
| 280 |
|
| 281 |
""" |
| 282 |
|
| 283 |
return SkipView(table, n) |
| 284 |
|
| 285 |
|
| 286 |
Table.skip = skip |
| 287 |
|
| 288 |
|
| 289 |
class SkipView(Table): |
| 290 |
|
| 291 |
def __init__(self, source, n): |
| 292 |
self.source = source |
| 293 |
self.n = n |
| 294 |
|
| 295 |
def __iter__(self): |
| 296 |
return iterskip(self.source, self.n) |
| 297 |
|
| 298 |
|
| 299 |
def iterskip(source, n): |
| 300 |
return itertools.islice(source, n, None) |
| 301 |
|
| 302 |
|
| 303 |
def prefixheader(table, prefix): |
| 304 |
"""Prefix all fields in the table header.""" |
| 305 |
|
| 306 |
return PrefixHeaderView(table, prefix) |
| 307 |
|
| 308 |
|
| 309 |
Table.prefixheader = prefixheader |
| 310 |
|
| 311 |
|
| 312 |
class PrefixHeaderView(Table): |
| 313 |
|
| 314 |
def __init__(self, table, prefix): |
| 315 |
self.table = table |
| 316 |
self.prefix = prefix |
| 317 |
|
| 318 |
def __iter__(self): |
| 319 |
it = iter(self.table) |
| 320 |
try: |
| 321 |
hdr = next(it) |
| 322 |
except StopIteration: |
| 323 |
return |
| 324 |
outhdr = tuple((text_type(self.prefix) + text_type(f)) for f in hdr) |
| 325 |
yield outhdr |
| 326 |
for row in it: |
| 327 |
yield row |
| 328 |
|
| 329 |
|
| 330 |
def suffixheader(table, suffix): |
| 331 |
"""Suffix all fields in the table header.""" |
| 332 |
|
| 333 |
return SuffixHeaderView(table, suffix) |
| 334 |
|
| 335 |
|
| 336 |
Table.suffixheader = suffixheader |
| 337 |
|
| 338 |
|
| 339 |
class SuffixHeaderView(Table): |
| 340 |
|
| 341 |
def __init__(self, table, suffix): |
| 342 |
self.table = table |
| 343 |
self.suffix = suffix |
| 344 |
|
| 345 |
def __iter__(self): |
| 346 |
it = iter(self.table) |
| 347 |
try: |
| 348 |
hdr = next(it) |
| 349 |
except StopIteration: |
| 350 |
return |
| 351 |
outhdr = tuple((text_type(f) + text_type(self.suffix)) for f in hdr) |
| 352 |
yield outhdr |
| 353 |
for row in it: |
| 354 |
yield row |
| 355 |
|
| 356 |
|
| 357 |
def sortheader(table, reverse=False, missing=None): |
| 358 |
"""Re-order columns so the header is sorted. |
| 359 |
|
| 360 |
.. versionadded:: 1.1.0 |
| 361 |
|
| 362 |
""" |
| 363 |
|
| 364 |
return SortHeaderView(table, reverse, missing) |
| 365 |
|
| 366 |
|
| 367 |
Table.sortheader = sortheader |
| 368 |
|
| 369 |
|
| 370 |
class SortHeaderView(Table): |
| 371 |
|
| 372 |
def __init__(self, table, reverse, missing): |
| 373 |
self.table = table |
| 374 |
self.reverse = reverse |
| 375 |
self.missing = missing |
| 376 |
|
| 377 |
def __iter__(self): |
| 378 |
it = iter(self.table) |
| 379 |
try: |
| 380 |
hdr = next(it) |
| 381 |
except StopIteration: |
| 382 |
return |
| 383 |
shdr = sorted(hdr) |
| 384 |
indices = asindices(hdr, shdr) |
| 385 |
transform = rowgetter(*indices) |
| 386 |
|
| 387 |
# yield the transformed header |
| 388 |
yield tuple(shdr) |
| 389 |
|
| 390 |
# construct the transformed data |
| 391 |
missing = self.missing |
| 392 |
for row in it: |
| 393 |
try: |
| 394 |
yield transform(row) |
| 395 |
except IndexError: |
| 396 |
# row is short, let's be kind and fill in any missing fields |
| 397 |
yield tuple(row[i] if i < len(row) else missing |
| 398 |
for i in indices) |